using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Storage;
using library;

namespace Using3DModels
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    /// 

    public struct VertexMultitextured
    {
        public Vector3 Position;
        public Vector3 Normal;
        public Vector4 TextureCoordinate;
        public Vector4 TexWeights;

        public static int SizeInBytes = (3 + 3 + 4 + 4) * sizeof(float);
        public static VertexElement[] VertexElements = new VertexElement[]
         {
             new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0 ),
             new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0 ),
             new VertexElement(sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0 ),
             new VertexElement(sizeof(float) * 10, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1 ),
         };
    }

    public class Game1 : Microsoft.Xna.Framework.Game
    {

        private struct Billboard
        {
            public const float BILLBOARD_SIZE = 2f;

            public Texture2D texture;
            public VertexBuffer vertexBuffer;
            public IndexBuffer indexBuffer;
        }

        
        private static void ConvertBuffer(float[,] from, byte[] to)
        {
            const int bytesPerSample = 2;
            int channels = from.GetLength(0);
            int samplesPerBuffer = from.GetLength(1);

            // Make sure the buffer sizes are correct
            System.Diagnostics.Debug.Assert(to.Length == samplesPerBuffer * channels * bytesPerSample, "Buffer sizes are mismatched.");

            for (int i = 0; i < samplesPerBuffer; i++)
            {
                for (int c = 0; c < channels; c++)
                {
                    // First clamp the value to the [-1.0..1.0] range
                    float floatSample = MathHelper.Clamp(from[c, i], -1.0f, 1.0f);

                    // Convert it to the 16 bit [short.MinValue..short.MaxValue] range
                    short shortSample = (short)(floatSample >= 0.0f ? floatSample * short.MaxValue : floatSample * short.MinValue * -1);

                    // Calculate the right index based on the PCM format of interleaved samples per channel [L-R-L-R]
                    int index = i * channels * bytesPerSample + c * bytesPerSample;

                    // Store the 16 bit sample as two consecutive 8 bit values in the buffer with regard to endian-ness
                    if (!BitConverter.IsLittleEndian)
                    {
                        to[index] = (byte)(shortSample >> 8);
                        to[index + 1] = (byte)shortSample;
                    }
                    else
                    {
                        to[index] = (byte)shortSample;
                        to[index + 1] = (byte)(shortSample >> 8);
                    }
                }
            }
        }

        private const int SampleRate = 42100;
        private const int ChannelsCount = 2;
        private DynamicSoundEffectInstance _instance;

        public const int SamplesPerBuffer = 1000;
        private float[,] _workingBuffer;
        private byte[] _xnaBuffer;

        private double _time = 3.0;
        private double _frequency;

        SoundEffect turbosound;

        SoundEffectInstance instance;

        SoundEffect bov;


        GraphicsDevice device;


        private Effect billboardeffect;
        private Billboard billboard;

        int terrainWidth;
        int terrainLength;
        float[,] heightData;
        float[,] heightData1;
        float[,] heightData2;
        float[,] heightData3;
        float[,] heightData4;
        float[,] heightData5;
        float[,] heightData6;
        float[,] heightData7;
        float[,] heightData8;
        float[,] heightData9;
        float[,] heightData10;
        float[,] heightData11;
        float[,] heightData12;
        float[,] heightData13;
        float[,] heightData14;
        float[,] heightData15;
        float[,] heightData16;


        int g = 1;

        int f;


        VertexBuffer terrainVertexBuffer;
        IndexBuffer terrainIndexBuffer;
        VertexBuffer terrainVertexBuffer2;
        IndexBuffer terrainIndexBuffer2;
        VertexBuffer terrainVertexBuffer3;
        IndexBuffer terrainIndexBuffer3;
        VertexBuffer terrainVertexBuffer4;
        IndexBuffer terrainIndexBuffer4;
        VertexBuffer terrainVertexBuffer5;
        IndexBuffer terrainIndexBuffer5;
        VertexBuffer terrainVertexBuffer6;
        IndexBuffer terrainIndexBuffer6;
        VertexBuffer terrainVertexBuffer7;
        IndexBuffer terrainIndexBuffer7;
        VertexBuffer terrainVertexBuffer8;
        IndexBuffer terrainIndexBuffer8;
        VertexBuffer terrainVertexBuffer9;
        IndexBuffer terrainIndexBuffer9;
        VertexBuffer terrainVertexBuffer10;
        IndexBuffer terrainIndexBuffer10;
        VertexBuffer terrainVertexBuffer11;
        IndexBuffer terrainIndexBuffer11;
        VertexBuffer terrainVertexBuffer12;
        IndexBuffer terrainIndexBuffer12;
        VertexBuffer terrainVertexBuffer13;
        IndexBuffer terrainIndexBuffer13;
        VertexBuffer terrainVertexBuffer14;
        IndexBuffer terrainIndexBuffer14;
        VertexBuffer terrainVertexBuffer15;
        IndexBuffer terrainIndexBuffer15;
        VertexBuffer terrainVertexBuffer16;
        IndexBuffer terrainIndexBuffer16;


        VertexDeclaration terrainVertexDeclaration;


        Effect effect;
      
        

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        KeyboardState KeyboardState;
        MouseState MouseState;

        public customvehicle currentcustomvehicle;
        public vehicle currentvehicle;
        public engine currentengine;
        public map currentmap;
        public carshop currentcarshop;
        public partshop currentpartshop;
        public part currentpart;
        public opponent currentopponent;

        Texture2D boost;
        Texture2D needlered;
        Texture2D kmh;
        Texture2D rpmgauge;
        Texture2D mainmenu;
        Texture2D arrow;
        Texture2D currenttexture1;
        Texture2D currenttexture2;
        Texture2D currenttexture3;
        Texture2D currenttexture4;
        Texture2D heightMap;
        Texture2D bluepixel;
        Texture2D redpixel;
        Texture2D yellowpixel;

        double[] torquevector = new double[3000];
        double[] hpvector = new double[3000];
        double[] boostvector = new double[3000];

        public double textureheight1;
        public double textureheight2;
        public double textureheight3;

        double time = 0;

        double distance;
        double tyredistancef;
        double tyredistancer;
        double surface = 1;  // 1 = tarmac  2 = gravel  3 = wet dirt   4 = icy
        double spinftyrespeed;
        double spinrtyrespeed;

        double distance2;
        double tyredistance2;

        int camera = 1;

        public double[] randomvector = new double[32];
        public double[] randomvector2 = new double[100];

        public int[] checkpointx = new int[30];
        public int[] checkpointy = new int[30];
        public int[] carshoppositionx = new int[6];
        public int[] carshoppositiony = new int[6];
        public int[] carshoppositionz = new int[6];
        public int[] partshoppositionx = new int[2];
        public int[] partshoppositiony = new int[2];
        public int[] partshoppositionz = new int[2];
        int direction = 1;  // 1 = forward  2 = reversing

        double h1;
        double h2;
        double h3;
        double h4;
        double bb = 0;

        bool go = true;

        Vector3 positionvector;
        Vector3 cameraposition;
        Vector3 cameradirection;

        int arrowy = 200;
        int arrowx = 200;

        double trap1;
        double trap2;
        double trap3;
        double trap4;
        double trap5;

        int checkpoint;

        double positionx = -1;
        double positiony = 0;
        double positionz = 0;

        double positionx2 = -48.5;
        double positiony2 = 36;
        double positionz2 = 0;

        bool stationary = true;

        bool finish = true;

        double floorrf = 0;
        double floorlf = 0;
        double floorrb = 0;
        double floorlb = 0;

        public double relativeheight;
        public double relativescale;
        double worlddistance;

        double menu = 1;
        int counter = 0;
        int level = 100;
        int opponent = 0;

        double speed = 0;
        double speedx = 0;
        double speedy = 0;
        double speedz = 0;
        double acceleration = 0;
        double torque = 0;
        public double maxtorque = 0;
        double currentboost;
        double ratio = 30;
        double drag = 0;
        public double mass = 1400;
        double rollingres = 0;
        double dx = 0;
        double dy = 1;
        double dz = 0;
        double dxp = 0;
        double dyp = 0;
        double dzp = 0;
        double steer = 0;  //angular speed omega
        double steerforce = 0;
        double angle = 0;
        double xangle = 0;
        double yangle = 0;
        double x2angle = 0;
        double y2angle = 0;
        double horizontalangle;
        double gravitysteer;
        double slopeangle;
        double gravityacceleration;
        double wheelangle;
        double wheelmoif; //wheel moment of inertia
        double wheelmoir;

        double speed2 = 0;
        double acceleration2 = 0;
        double torque2 = 0;
        public double maxtorque2 = 0;
        double currentboost2;
        double ratio2 = 30;
        double drag2 = 0;
        public double mass2 = 1400;
        double rollingres2 = 0;
        double xangle2 = 0;
        double yangle2 = 0;
        double wheelmoif2; //wheel moment of inertia
        double wheelmoir2;


        double frontwheeldrive = 0;

        double frontwheeldrive2 = 0;

        double wheelradiusfront;
        double wheelradiusrear;
        double offsetlength;
        double offsetheight;

        double wheelradiusfront2;
        double wheelradiusrear2;
        double offsetlength2;
        double offsetheight2;

        double wheelbasewidth;
        double wheelbaselength;
        double massheight;  //centre of mass
        double masswidth;     //uniform mass body
        double masslength;
        double loadtransfer;
        double loadtransferside = 0;

        double wheelbasewidth2;
        double wheelbaselength2;
        double massheight2;  //centre of mass
        double masswidth2;     //uniform mass body
        double masslength2;
        double loadtransfer2;


        double momentofinertia = 0;

        double angularacceleration;

        double frontweight;

        double frontweight2;

        double wheelposrfx;
        double wheelposrbx;
        double wheelposlfx;
        double wheelposlbx;

        double wheelposrfx2;
        double wheelposrbx2;
        double wheelposlfx2;
        double wheelposlbx2;

        double wheelposrfy;
        double wheelposrby;
        double wheelposlfy;
        double wheelposlby;

        double wheelposrfy2;
        double wheelposrby2;
        double wheelposlfy2;
        double wheelposlby2;

        double wheelposrfz = 1;
        double wheelposrbz = 1;
        double wheelposlfz = 1;
        double wheelposlbz = 1;

        double camangle;
        double camlift;

        double camangle2;
        double camlift2;

        double wheelspeedrfz = 0;
        double wheelspeedrbz = 0;
        double wheelspeedlfz = 0;
        double wheelspeedlbz = 0;

        double gravity = 9.82;

        double springrfpos = 0;
        double springrbpos = 0;
        double springlfpos = 0;
        double springlbpos = 0;

        double springrfpos2 = 0;
        double springrbpos2 = 0;
        double springlfpos2 = 0;
        double springlbpos2 = 0;

        double springrfspeed = 0;
        double springrbspeed = 0;
        double springlfspeed = 0;
        double springlbspeed = 0;

        double springrfspeed2 = 0;
        double springrbspeed2 = 0;
        double springlfspeed2 = 0;
        double springlbspeed2 = 0;

        public double springstiffnessf;
        public double springstiffnessb;
        public double springdampingf;
        public double springdampingb;

        public double springstiffnessf2;
        public double springstiffnessb2;
        public double springdampingf2;
        public double springdampingb2;

        double collisionfzrf = 0;
        double collisionfzlf = 0;
        double collisionfzrb = 0;
        double collisionfzlb = 0;

        double driftangle = 0;
        double driftanglespeed = 0;
        double rollangle;
        double turningradius = 8;

        double a;
        double b;
        double c;
        double d;
        double e;
        bool lol = false;


        bool rollover = false;

        int gas = 0;

        double[] ratiovector = new double[15];
        double finaldriveratio;

        double[] ratiovector2 = new double[15];
        double finaldriveratio2;


        double shiftingtime;
        double rpm = 0;
        double idlerpm;
        int gear = 3;
        int gears = 6;
        double maxrpm;
        Vector4 lrpm;
        Vector4 urpm;
        double arpm;
        double launchrpm;
        double maxboost;
        double airfuelratio; // how manny units of fuel per unit of air
        double turbosize; //size of turbo (inducer diameter)
        double turbomax; //maximum boost of turbo
        double ve;  //volumetric efficiency
        double turbolag; // time to spool up 1 bar of boost(seconds)
        double pistonacceleration;
        double gaspedal;
        double gaspedalsensitivity = 1;
        bool engineknock = false;


        double shiftingtime2;
        double rpm2 = 0;
        int gear2;
        int gears2;
        double maxrpm2;
        double launchrpm2;
        double maxboost2;
        double airfuelratio2; // how manny units of fuel per unit of air
        double turbosize2; //size of turbo (inducer diameter)
        double ve2;  //volumetric efficiency
        double turbolag2; // time to spool up 1 bar of boost(seconds)
        double pistonacceleration2;



        double exhaustmax = 400;   //maximum airflow of exhaust(litre per second)
        double intakemax = 5000;   //maximum airflow of intake(litre per second)
        double pistonweight = 0.23;
        double stroke;
        double bore;
        double injectorsize;
        bool turbo;
        bool twinturbo;
        bool supercharger;
        bool nos;
        bool exhaust;
        bool sportexhaust;
        bool racingexhaust;
        bool cai;
        bool customecu;
        bool ecu;
        bool forgedpistons;
        bool titaniumpistons;
        bool racingmanifold;
        bool forgedconnectingrods;
        bool titaniumconnectingrods;
        bool valvesprings;
        bool valves;
        bool camlobes;
        bool ported;
        bool waterinjection;
        bool methanolinjection;
        bool variablesparkplug;
        bool intercooler;
        bool raceintercooler;
        int cylinders;
        int stroketype;


        double exhaustmax2 = 400;   //maximum airflow of exhaust(litre per second)
        double intakemax2 = 5000;   //maximum airflow of intake(litre per second)
        double pistonweight2 = 0.23;
        double stroke2;
        double injectorsize2;
        bool turbo2;
        bool twinturbo2;
        bool supercharger2;
        bool exhaust2;
        bool sportexhaust2;
        bool racingexhaust2;
        bool cai2;
        bool racingmanifold2;
        int stroketype2;


        BoundingBox boundingbox1;

        Random random = new Random();
        

        Vector3 meshvector;
        Vector3 carshopvector;
        Vector3 partshopvector;
        Vector3 camerapos;
        Vector3 enginerestriction;

        Vector3 enginerestriction2;

        Vector4 Tyretype;      //normal = 4.3-4.7 sport = 4.7-5 drag radials = 5.1 slicks = 5.3+
        double tyrewidthf;  // 0.2 base(m)
        double tyrewidthr;  // 0.2 base(m)

        Vector4 Tyretype2;      //normal = 4.3-4.7 sport = 4.7-5 drag radials = 5.1 slicks = 5.3+
        double tyrewidthf2;  // 0.2 base(m)
        double tyrewidthr2;  // 0.2 base(m)

        bool collision = false;

        double Cv;
        double frontalarea;
        double griprf = 0;
        double griplf = 0;
        double griprb = 0;
        double griplb = 0;
        double tyrebasegrip;

        double Cv2;
        double frontalarea2;
        double griprf2 = 0;
        double griplf2 = 0;
        double griprb2 = 0;
        double griplb2 = 0;
        double tyrebasegrip2;

        int pause = 0;
        int pause2 = 10;
        int pause3 = 0;
        int pause4 = 0;
        int pause5 = 0;
        int controls = 1;
        double deadzone = 0.005;

        double displacement;
        double friction;
        double engineefficiency = 0.29;
        public double compression;
        public string enginetype;
        public string info;
        public string fuel;
        public int octane = 95;
        double peakve;
        double currentpeakve;
        double speedlimiter;

        double displacement2;
        double friction2;
        double engineefficiency2;
        public double compression2;
        public string fuel2;
        double peakve2;
        double speedlimiter2;


        public Vector4 rpm0;
        public Vector4 rpm250;
        public Vector4 rpm500;
        public Vector4 rpm750;
        public Vector4 rpm1000;
        public Vector4 rpm1250;
        public Vector4 rpm1500;
        public Vector4 rpm1750;
        public Vector4 rpm2000;
        public Vector4 rpm2250;
        public Vector4 rpm2500;
        public Vector4 rpm2750;
        public Vector4 rpm3000;
        public Vector4 rpm3250;
        public Vector4 rpm3500;
        public Vector4 rpm3750;
        public Vector4 rpm4000;
        public Vector4 rpm4250;
        public Vector4 rpm4500;
        public Vector4 rpm4750;
        public Vector4 rpm5000;
        public Vector4 rpm5250;
        public Vector4 rpm5500;
        public Vector4 rpm5750;
        public Vector4 rpm6000;
        public Vector4 rpm6250;
        public Vector4 rpm6500;
        public Vector4 rpm6750;
        public Vector4 rpm7000;
        public Vector4 rpm7250;
        public Vector4 rpm7500;
        public Vector4 rpm7750;
        public Vector4 rpm8000;
        public Vector4 rpm8250;
        public Vector4 rpm8500;
        public Vector4 rpm8750;
        public Vector4 rpm9000;
        public Vector4 rpm9250;
        public Vector4 rpm9500;
        public Vector4 rpm9750;
        public Vector4 rpm10000;

        public Vector4 rpm02;
        public Vector4 rpm2502;
        public Vector4 rpm5002;
        public Vector4 rpm7502;
        public Vector4 rpm10002;
        public Vector4 rpm12502;
        public Vector4 rpm15002;
        public Vector4 rpm17502;
        public Vector4 rpm20002;
        public Vector4 rpm22502;
        public Vector4 rpm25002;
        public Vector4 rpm27502;
        public Vector4 rpm30002;
        public Vector4 rpm32502;
        public Vector4 rpm35002;
        public Vector4 rpm37502;
        public Vector4 rpm40002;
        public Vector4 rpm42502;
        public Vector4 rpm45002;
        public Vector4 rpm47502;
        public Vector4 rpm50002;
        public Vector4 rpm52502;
        public Vector4 rpm55002;
        public Vector4 rpm57502;
        public Vector4 rpm60002;
        public Vector4 rpm62502;
        public Vector4 rpm65002;
        public Vector4 rpm67502;
        public Vector4 rpm70002;
        public Vector4 rpm72502;
        public Vector4 rpm75002;
        public Vector4 rpm77502;
        public Vector4 rpm80002;
        public Vector4 rpm82502;
        public Vector4 rpm85002;
        public Vector4 rpm87502;
        public Vector4 rpm90002;
        public Vector4 rpm92502;
        public Vector4 rpm95002;
        public Vector4 rpm97502;
        public Vector4 rpm100002;


        private SpriteFont font;

        /// <summary>
        /// Stores the model that we are going to draw.
        /// </summary>
        public Model model;
        public Model model2;

        public Model dynomodel;


        private Model modelspring;
        private Model modelspring2;


        private Model wheelfront;
        private Model wheelrear;

        private Model wheelfront2;
        private Model wheelrear2;

        public Model garage;

        public Model junkyard;

        public Model dragstrip;

        public Model ground;

        public Model portal;

        public Model collisionmodel;


        /// <summary>
        /// Stores the world matrix for the model, which transforms the 
        /// model to be in the correct position, scale, and rotation
        /// in the game world.
        /// </summary>
        /// 
        private Matrix world0 = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix world02 = Matrix.CreateTranslation(new Vector3((float)-48.5, 37, 0));
        private Matrix world = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheelrf = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheelrb = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheellf = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheellb = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheelrf2 = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheelrb2 = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheellf2 = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldwheellb2 = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldspringrf = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldspringrb = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldspringlf = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldspringlb = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix worldgarage = Matrix.CreateTranslation(new Vector3(-2, 20, 0));
        private Matrix worldgarage2 = Matrix.CreateTranslation(new Vector3(-52, 20, 0));
        private Matrix worldground = Matrix.CreateTranslation(new Vector3(-250, -250, (float)-0.01));

        public Matrix worldt1;
        public Matrix worldt2;
        public Matrix worldt3;
        public Matrix worldt4;
        public Matrix worldt5;
        public Matrix worldt6;
        public Matrix worldt7;
        public Matrix worldt8;
        public Matrix worldt9;
        public Matrix worldt10;
        public Matrix worldt11;
        public Matrix worldt12;
        public Matrix worldt13;
        public Matrix worldt14;
        public Matrix worldt15;
        public Matrix worldt16;

        public Matrix check1;
        public Matrix check2;


        /// <summary>
        /// Stores the view matrix for the model, which gets the model
        /// in the right place, relative to the camera.
        /// </summary>
        private Matrix view = Matrix.CreateLookAt(new Vector3(0, -2, 1), new Vector3(0, 0, 0), Vector3.UnitY);

        /// <summary>
        /// Stores the projection matrix, which gets the model projected
        /// onto the screen in the correct way.  Essentially, this defines the
        /// properties of the camera you are using.
        /// </summary>
        private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(55), 1680f / 1050f, 0.1f, 400f);


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 1680;
            graphics.PreferredBackBufferHeight = 1050;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            
            base.Initialize();

            InitBillboard(Billboard.BILLBOARD_SIZE, Billboard.BILLBOARD_SIZE, new Vector3(0.0f, Billboard.BILLBOARD_SIZE * 0.5f, 0.0f));
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);


            _instance = new DynamicSoundEffectInstance(SampleRate, AudioChannels.Stereo);

            _workingBuffer = new float[ChannelsCount, SamplesPerBuffer];
            const int bytesPerSample = 2;
            _xnaBuffer = new byte[ChannelsCount * SamplesPerBuffer * bytesPerSample];

            _instance.Play();


            billboard.texture = Content.Load<Texture2D>("grass");

            billboardeffect = Content.Load<Effect>("billboardeffect");
            billboardeffect.CurrentTechnique = billboardeffect.Techniques["Albedo"];

            turbosound = Content.Load<SoundEffect>("turbo");

            instance = turbosound.CreateInstance();

            instance.IsLooped = true;

            bov = Content.Load<SoundEffect>("rb 25 BOV");

            device = GraphicsDevice;

            effect = Content.Load<Effect>("effects");

            currentmap = Content.Load<map>("maps/freeroam/blank_map");
            newmap();



            ground = Content.Load<Model>("ground");


            spriteBatch = new SpriteBatch(GraphicsDevice);


            modelspring = Content.Load<Model>("spring");
            modelspring2 = Content.Load<Model>("spring");

            garage = Content.Load<Model>("garage");
            junkyard = Content.Load<Model>("junkyard");
            dynomodel = Content.Load<Model>("dyno");
            portal = Content.Load<Model>("portal");
            dragstrip = Content.Load<Model>("highway");

            font = Content.Load<SpriteFont>("Font1");

            boost = Content.Load<Texture2D>("boost");
            needlered = Content.Load<Texture2D>("needlered");
            kmh = Content.Load<Texture2D>("kmh");
            rpmgauge = Content.Load<Texture2D>("rpmgauge");
            mainmenu = Content.Load<Texture2D>("menu");
            arrow = Content.Load<Texture2D>("arrow");
            bluepixel = Content.Load<Texture2D>("bluepixel");
            redpixel = Content.Load<Texture2D>("redpixel");
            yellowpixel = Content.Load<Texture2D>("yellowpixel");


            for (int i = 0; i < randomvector2.Length; i++)         // needs to find number of carshops automaticly!
            {
                randomvector2[i] = random.NextDouble();
            }
             

            currentvehicle = Content.Load<vehicle>("cars/continent sedan 10s 1");   // load car

            newvehicle();
            newopponent();

            for (int i = 0; i < 6; i++)         // needs to find number of carshops automaticly!
            {
                currentcarshop = Content.Load<carshop>("carshops/" + Convert.ToString(i + 1,10));
                carshoppositionx[i] = currentcarshop.x;
                carshoppositiony[i] = currentcarshop.y;
                carshoppositionz[i] = currentcarshop.z;
            }
            for (int i = 0; i < 2; i++)     // same here 
            {
                currentpartshop = Content.Load<partshop>("partshops/" + Convert.ToString(i + 1, 10));
                partshoppositionx[i] = currentpartshop.xx;
                partshoppositiony[i] = currentpartshop.yy;
                partshoppositionz[i] = currentpartshop.zz;
            }

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
        }

        private void InitBillboard(float width, float height, Vector3 position)
        {
            float x = width * 0.5f;
            float y = height * 0.5f;

            Vector3 upperLeft = new Vector3(-x, y, 0.0f);
            Vector3 upperRight = new Vector3(x, y, 0.0f);
            Vector3 lowerLeft = new Vector3(-x, -y, 0.0f);
            Vector3 lowerRight = new Vector3(x, -y, 0.0f);

            VertexPositionTexture[] vertices =
            {
                new VertexPositionTexture(position + upperLeft,  new Vector2(0.0f, 0.0f)),  // 0
                new VertexPositionTexture(position + upperRight, new Vector2(1.0f, 0.0f)),  // 1
                new VertexPositionTexture(position + lowerLeft,  new Vector2(0.0f, 1.0f)),  // 2
                new VertexPositionTexture(position + lowerRight, new Vector2(1.0f, 1.0f)),  // 3
            };

            billboard.vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionTexture), vertices.Length, BufferUsage.WriteOnly);
            billboard.vertexBuffer.SetData(vertices);

            short[] indices =
            {
                0, 1, 2,
                2, 1, 3
            };

            billboard.indexBuffer = new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, indices.Length, BufferUsage.WriteOnly);
            billboard.indexBuffer.SetData(indices);
        }

        private static readonly Random Rng = new Random();

        double SineWave(double time, double frequency)
        {
            if (KeyboardState.IsKeyDown(Keys.Up) || MouseState.LeftButton == ButtonState.Pressed)
                bb = bb + 0.1;
            else
                bb = bb - 0.1;
            if (bb > 1)
                bb = 1;
            if (bb < 0)
                bb = 0;
            a = Math.Sin(time * 2) * 0.3;
            a = a + Math.Sin(time / 2) * 0.3;
            a = a + Math.Pow(Math.Sin(time + 0.2), 5) * 0.3 * bb;   // 5 = 4cyl?    
            a = a + Math.Pow(Math.Sin(time - 0.2), 14) * 0.2 * bb; 
            a = a + Math.Pow(Math.Sin(time - 0.2), 10) * 0.1;      
            return a;
        }

        protected BoundingBox UpdateBoundingBox(Model model, Matrix worldTransform)
        {
            // Initialize minimum and maximum corners of the bounding box to max and min values
            Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
            Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

            // For each mesh of the model
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                {
                    // Vertex buffer parameters
                    int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride;
                    int vertexBufferSize = meshPart.NumVertices * vertexStride;

                    // Get vertex data as float
                    float[] vertexData = new float[vertexBufferSize / sizeof(float)];
                    meshPart.VertexBuffer.GetData<float>(vertexData);

                    // Iterate through vertices (possibly) growing bounding box, all calculations are done in world space
                    for (int i = 0; i < vertexBufferSize / sizeof(float); i += vertexStride / sizeof(float))
                    {
                        Vector3 transformedPosition = Vector3.Transform(new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]), worldTransform);

                        min = Vector3.Min(min, transformedPosition);
                        max = Vector3.Max(max, transformedPosition);
                    }
                }
            }

            // Create and return bounding box
            return boundingbox1 = new BoundingBox(min, max);
        }



        public void newmap()
        {
            heightMap = Content.Load<Texture2D>(currentmap.totalmap);
            g = 1;
            checkpointx = currentmap.checkpointx;
            if (checkpointx[0] == -56)
                a = a;
            checkpointy = currentmap.checkpointy;
            positionx2 = -48.5;
            positiony2 = 36;
            speed2 = 0;
            positionx = currentmap.positionx;
            positiony = currentmap.positiony;
            dx = currentmap.dx;
            dy = currentmap.dy;
            relativeheight = currentmap.relativeheight;
            relativescale = currentmap.relativescale;
            currenttexture1 = Content.Load<Texture2D>(currentmap.currenttexture1);
            currenttexture2 = Content.Load<Texture2D>(currentmap.currenttexture2);
            currenttexture3 = Content.Load<Texture2D>(currentmap.currenttexture3);
            currenttexture4 = Content.Load<Texture2D>(currentmap.currenttexture4);
            textureheight1 = currentmap.textureheight1;
            textureheight2 = currentmap.textureheight2;
            textureheight3 = currentmap.textureheight3;
            surface = currentmap.surface;
            LoadVertices();
            g = 2;
            heightData = heightData2;
            LoadVertices();
            g = 3;
            heightData = heightData3;
            LoadVertices();
            g = 4;
            heightData = heightData4;
            LoadVertices();
            g = 5;
            heightData = heightData5;
            LoadVertices();
            g = 6;
            heightData = heightData6;
            LoadVertices();
            g = 7;
            heightData = heightData7;
            LoadVertices();
            g = 8;
            heightData = heightData8;
            LoadVertices();
            g = 9;
            heightData = heightData9;
            LoadVertices();
            g = 10;
            heightData = heightData10;
            LoadVertices();
            g = 11;
            heightData = heightData11;
            LoadVertices();
            g = 12;
            heightData = heightData12;
            LoadVertices();
            g = 13;
            heightData = heightData13;
            LoadVertices();
            g = 14;
            heightData = heightData14;
            LoadVertices();
            g = 15;
            heightData = heightData15;
            LoadVertices();
            g = 16;
            heightData = heightData16;
            LoadVertices();

            terrainWidth = terrainWidth - 1;
            terrainLength = terrainLength - 1;

            worldt1 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3(0, 0, 0));
            worldt2 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((terrainWidth) * (float)relativescale, 0, 0));
            worldt3 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3(0, (terrainLength) * (float)relativescale, 0));
            worldt4 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((terrainWidth) * (float)relativescale, (terrainLength) * (float)relativescale, 0));
            worldt5 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((2 * terrainWidth) * (float)relativescale, 0, 0));
            worldt6 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3(0, (2 * terrainLength) * (float)relativescale, 0));
            worldt7 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((2 * terrainWidth) * (float)relativescale, (terrainLength) * (float)relativescale, 0));
            worldt8 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((terrainWidth) * (float)relativescale, (2 * terrainLength) * (float)relativescale, 0));
            worldt9 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((2 * terrainWidth) * (float)relativescale, (2 * terrainLength) * (float)relativescale, 0));
            worldt10 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((3 * terrainWidth - 1) * (float)relativescale, 0, (float)+0.003));
            worldt11 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3(0, (3 * terrainLength - 1) * (float)relativescale, (float)+0.003));
            worldt12 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((3 * terrainWidth - 1) * (float)relativescale, (terrainLength) * (float)relativescale, (float)+0.001));
            worldt13 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((terrainWidth) * (float)relativescale, (3 * terrainLength - 1) * (float)relativescale, (float)+0.001));
            worldt14 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((3 * terrainWidth - 1) * (float)relativescale, (2 * terrainLength) * (float)relativescale, (float)+0.002));
            worldt15 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((2 * terrainWidth) * (float)relativescale, (3 * terrainLength - 1) * (float)relativescale, (float)+0.001));
            worldt16 = Matrix.CreateScale((float)relativescale) * Matrix.CreateRotationX((float)(Math.PI / 2)) * Matrix.CreateTranslation(new Vector3((3 * terrainWidth - 1) * (float)relativescale, (3 * terrainLength - 1) * (float)relativescale,0));


            LoadHeightData(heightMap);




            speedy = dy * 0.21;
            speedx = dx * 0.21;
            stationary = false;
            direction = 1;
            go = false;
            trap1 = 0;
            trap2 = 0;
            trap3 = 0;
            trap4 = 0;
            menu = 1;
            checkpoint = 0;
            if (checkpointx.Length > 1)
                finish = false;
            trap1 = 0;
            trap2 = 0;
            trap3 = 0;
            trap4 = 0;
            trap5 = 0;
            distance = 0;
            distance2 = 0;
            gear = 2;
            gear2 = 2;
            ratio = ratiovector[2] / (wheelradiusfront * frontwheeldrive + wheelradiusrear * (1 - frontwheeldrive)) * finaldriveratio;
            ratio2 = ratiovector2[2] / (wheelradiusfront2 * frontwheeldrive2 + wheelradiusrear2 * (1 - frontwheeldrive2)) * finaldriveratio2;
        }

        public void driveopponent()
        {
            acceleration2 = 0;
            torque2 = 0;


            rpm2 = speed2 * ratio2 * 60 / 2 / 3.14;

            if (Math.Abs(speed2) < 8 & rpm2 < launchrpm2)
                rpm2 = launchrpm2;

            if (rpm2 > maxrpm2 * 0.98)
            {
                gear2 = gear2 + 1;
                ratio2 = ratiovector2[gear2] / (wheelradiusfront2 * frontwheeldrive2 + wheelradiusrear2 * (1 - frontwheeldrive2)) * finaldriveratio2;
                pause5 = 0;
            }


            getengineparam2();
            if (turbo2 == false & supercharger2 == false)
            {
                currentboost2 = 0;
                maxboost2 = 0;
            }
            else
                maxboost2 = lrpm.Y + (rpm2 - arpm) / 250 * (urpm.Y - lrpm.Y);    //extrapolation of engine parameters


            b = rpm2;
            rpm2 = rpm2 - camangle2;
            getengineparam2();
            ve2 = lrpm.X + (rpm2 - arpm) / 250 * (urpm.X - lrpm.X);                  //extrapolation of engine parameters
            turbolag2 = lrpm.Z + (rpm2 - arpm) / 250 * (urpm.Z - lrpm.Z);

            pistonacceleration2 = stroke2 / 2000 * Math.Pow(2 * Math.PI * b / 60, 2);

            if (sportexhaust2)
                ve2 = ve2 + 0.02;
            else if (racingexhaust2)
                ve2 = ve2 + 0.04;
            if (racingmanifold2)
                ve2 = ve2 + 0.03;
            if (cai2)
                ve2 = ve2 + 0.01;
            if (racingexhaust2 & racingmanifold2 & cai2)   //removed "ported"
                ve2 = ve2 + 0.01;


            if (twinturbo2)
                turbolag2 = turbolag2 * 0.6;
            if (supercharger2)
                turbolag2 = 0.1;
            if (maxboost2 > enginerestriction2.Y & enginerestriction2.Y != 0)
                maxboost2 = enginerestriction2.Y;
            if (currentboost2 < maxboost2 & maxboost2 > 0 & turbolag2 > 0 & pause5 > shiftingtime2 * 60 / 2)           // turbo
                currentboost2 = currentboost2 + 1 / turbolag2 / 60;
            else if (currentboost2 > maxboost2)
                currentboost2 = maxboost2;
            else if (currentboost2 > 0)
            {
                currentboost2 = currentboost2 * 0.97 - 0.03;
            }

            if (fuel2 == "petrol")
            {
                engineefficiency2 = 0.31 * Math.Pow(compression2 / 11, 0.2);
                if (ve2 * rpm2 / 60 * displacement2 / 1000 / stroketype2 > intakemax2)         //intake limitation
                    ve2 = intakemax2 * 1000 * stroketype2 * 60 / displacement2 / rpm2;
                if (enginerestriction2.X < turbosize2 & enginerestriction2.X != 0)
                    d = enginerestriction2.X;
                else
                    d = turbosize2;
                a = Math.Pow((d / 2), 2) * Math.PI / 3 * 0.95;  // a = cfm of turbo
                if (twinturbo2)
                    a = a * 0.85;
                if ((ve2 + currentboost2) * rpm2 / 60 * displacement2 / 1000 / stroketype2 > a / 2.119)            // turbo limitations
                {
                    currentboost2 = a / 2.119 / rpm2 * 60 / displacement2 * 1000 * stroketype2 - ve2;
                }
                if (currentboost2 < 0)
                    currentboost2 = 0;
                if (ve2 * (1 + currentboost2) * rpm2 / 60 * displacement2 / 1000 / stroketype2 * 1.45 > exhaustmax2)
                    currentboost2 = exhaustmax2 * 1000 * stroketype2 * 60 / displacement2 / rpm2 / ve2 / 1.45 - 1;       //exhaust limitation     1.45: correcting factor for added fuel and exhaust temp
                if (pistonacceleration2 > 22000)
                    engineefficiency2 = engineefficiency2 * Math.Pow(22000 / pistonacceleration2, pistonweight2 / 1.5);  // piston acceleration
                maxtorque2 = (ve2 * (currentboost2 + 1)) * displacement2 / 1000 / stroketype2 * 690 * engineefficiency2;   //engine torque
                maxtorque2 = maxtorque2 * Math.Pow(12.5 / airfuelratio2, 0.3);
                if (airfuelratio2 < 12.5)
                    maxtorque2 = maxtorque2 * (airfuelratio2 / 12.5);
                if (maxtorque2 > enginerestriction2.Z & enginerestriction2.Z != 0)
                    maxtorque2 = enginerestriction2.Z;
                if (speed2 > speedlimiter2 & speedlimiter2 != 0)
                    maxtorque2 = 0;

                if (ve2 * (1 + currentboost2) * rpm2 * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771 > injectorsize2 * 0.9)
                    maxtorque2 = maxtorque2 * 0.9 * injectorsize2 / (ve2 * (1 + currentboost2) * rpm2 * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771);   // injector limitation

                if (b > camlift2)
                {
                    maxtorque2 = maxtorque2 * Math.Pow(camlift2 / b, 2.5);
                }
                if (b > camlift2 * 1.15)
                    maxtorque2 = 0;
            }

            rpm2 = b;

            if (pause5 < shiftingtime2 * 60)
                maxtorque2 = 0;

            if (rpm2 < maxrpm2)
                torque2 = maxtorque2 * friction2;

            mass2 = mass2 + wheelmoif2 + wheelmoir2;

            drag2 = Cv2 * 1.2 / 2 * frontalarea2 * speed2 * speed2 / mass2;              //drag=Cd*P*A/2*(v^2)/m
            rollingres2 = (0.02 + 3.24 * 0.002 * Math.Pow(Math.Abs(speed2) / 32 + 0.1, 3.2)) * (tyrewidthf2 + tyrewidthr2) / 2 / 0.22;

            acceleration2 = acceleration2 - drag2 - rollingres2;


            if (go == false)
                acceleration2 = 0;

            mass2 = mass2 - wheelmoif2 - wheelmoir2;


            



            tyredistance2 = tyredistance2 + speed2 / 60;

            if (go)
            {
                if (torque2 * frontwheeldrive2 / 2 * ratio2 / mass2 <= griprf2)
                    acceleration2 = acceleration2 + (torque2 * frontwheeldrive2 / 2 * ratio2 / mass2 - rollingres2 / 4);
                else
                    acceleration2 = acceleration2 + griprf2 * 0.9;

                if (torque2 * frontwheeldrive2 / 2 * ratio2 / mass2 <= griplf2)
                    acceleration2 = acceleration2 + (torque2 * frontwheeldrive2 / 2 * ratio2 / mass2 - rollingres2 / 4);
                else
                    acceleration2 = acceleration2 + griplf2 * 0.9;

                if (torque2 * (1 - frontwheeldrive2) / 2 * ratio2 / mass2 <= griprb2)
                    acceleration2 = acceleration2 + (torque2 * (1 - frontwheeldrive2) / 2 * ratio2 / mass2 - rollingres2 / 4);
                else
                    acceleration2 = acceleration2 + griprb2 * 0.9;

                if (torque2 * (1 - frontwheeldrive2) / 2 * ratio2 / mass2 <= griplb2)
                    acceleration2 = acceleration2 + (torque2 * (1 - frontwheeldrive2) / 2 * ratio2 / mass2 - rollingres2 / 4);
                else
                    acceleration2 = acceleration2 + griplb2 * 0.9;

                if ((springlbspeed2 + springrbspeed2) / 2 < 0 & acceleration2 > 1)
                    acceleration2 = acceleration2 + (springlbspeed2 + springrbspeed2);
            }

            loadtransfer2 = acceleration2 * massheight2 / wheelbaselength2 / gravity;
            speed2 = speed2 + acceleration2 / 60;
            positiony2 = positiony2 + speed2 / 60;




            springrfspeed2 = springrfspeed2 - springstiffnessf2 * springrfpos2 / mass2 / 60 - gravity / 2 * frontweight2 / 60 * (1 - loadtransfer2);         //suspension 

            springrfspeed2 = springrfspeed2 * springdampingf2;

            //left front


            springrbspeed2 = springrbspeed2 - springstiffnessb2 * springrbpos2 / mass2 / 60 - gravity / 2 * (1 - frontweight2) / 60 * (1 + loadtransfer2);         //suspension

            springrbspeed2 = springrbspeed2 * springdampingb2;

            //left back



            springlfspeed2 = springlfspeed2 - springstiffnessf2 * springlfpos2 / mass2 / 60 - gravity / 2 * frontweight2 / 60 * (1 - loadtransfer2);         //suspension 

            springlfspeed2 = springlfspeed2 * springdampingf2;

            // right front


            springlbspeed2 = springlbspeed2 - springstiffnessb2 * springlbpos2 / mass2 / 60 - gravity / 2 * (1 - frontweight2) / 60 * (1 + loadtransfer2);         //suspension 
                                      //right back
            springlbspeed2 = springlbspeed2 * springdampingb2;

            springrfpos2 = springrfpos2 + springrfspeed2 / 60;
            springrbpos2 = springrbpos2 + springrbspeed2 / 60;
            springlfpos2 = springlfpos2 + springlfspeed2 / 60;
            springlbpos2 = springlbpos2 + springlbspeed2 / 60;




            if (-springrfpos2 * springstiffnessf2 / tyrewidthf2 > 4 * 22300)
                griprf2 = 22300 * tyrewidthf2 * tyrewidthf2 / mass2 * tyrebasegrip2 + Math.Pow((3 * 22300 * tyrewidthf2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthf2;
            else if (-springrfpos2 * springstiffnessf2 / tyrewidthf2 > 22300)
                griprf2 = 22300 * tyrewidthf2 * tyrewidthf2 / mass2 * tyrebasegrip2 + Math.Pow((-springrfpos2 * springstiffnessf2 - 22300 * tyrewidthf2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthf2;
            else
                griprf2 = -springrfpos2 * springstiffnessf2 / mass2 * tyrebasegrip2 * tyrewidthf2;

            if (-springlfpos2 * springstiffnessf2 / tyrewidthf2 > 4 * 22300)
                griplf2 = 22300 * tyrewidthf2 * tyrewidthf2 / mass2 * tyrebasegrip2 + Math.Pow((3 * 22300 * tyrewidthf2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthf2;
            else if (-springlfpos2 * springstiffnessf2 / tyrewidthf2 > 22300)
                griplf2 = 22300 * tyrewidthf2 * tyrewidthf2 / mass2 * tyrebasegrip2 + Math.Pow((-springlfpos2 * springstiffnessf2 - 22300 * tyrewidthf2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthf2;
            else
                griplf2 = -springlfpos2 * springstiffnessf2 / mass2 * tyrebasegrip2 * tyrewidthf2;

            if (-springrbpos2 * springstiffnessb2 / tyrewidthr2 > 4 * 22300)
                griprb2 = 22300 * tyrewidthr2 * tyrewidthr2 / mass2 * tyrebasegrip2 + Math.Pow((3 * 22300 * tyrewidthr2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthr2;
            else if (-springrbpos2 * springstiffnessb2 / tyrewidthr2 > 22300)
                griprb2 = 22300 * tyrewidthr2 * tyrewidthr2 / mass2 * tyrebasegrip2 + Math.Pow((-springrbpos2 * springstiffnessb2 - 22300 * tyrewidthr2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthr2;
            else
                griprb2 = -springrbpos2 * springstiffnessb2 / mass2 * tyrebasegrip2 * tyrewidthr2;

            if (-springlbpos2 * springstiffnessb2 / tyrewidthr2 > 4 * 22300)
                griplb2 = 22300 * tyrewidthr2 * tyrewidthr2 / mass2 * tyrebasegrip2 + Math.Pow((3 * 22300 * tyrewidthr2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthr2;
            else if (-springlbpos2 * springstiffnessb2 / tyrewidthr2 > 22300)
                griplb2 = 22300 * tyrewidthr2 * tyrewidthr2 / mass2 * tyrebasegrip2 + Math.Pow((-springlbpos2 * springstiffnessb2 - 22300 * tyrewidthr2), 0.85) / mass2 * tyrebasegrip2 * tyrewidthr2;
            else
                griplb2 = -springlbpos2 * springstiffnessb2 / mass2 * tyrebasegrip2 * tyrewidthr2;






            xangle2 = Math.Asin((springrfpos2 - springrbpos2) / wheelbaselength2);
            yangle2 = Math.Asin((springlfpos2 - springlbpos2) / wheelbaselength2);





            wheelposrfx2 = positionx2 + wheelbasewidth2 / 2;
            wheelposrfy2 = positiony2 + wheelbaselength2 / 2;

            wheelposrbx2 = positionx2 + wheelbasewidth2 / 2;                // calculate position of each wheel
            wheelposrby2 = positiony2 - wheelbaselength2 / 2;

            wheelposlfx2 = positionx2 - wheelbasewidth2 / 2;
            wheelposlfy2 = positiony2 + wheelbaselength2 / 2;

            wheelposlbx2 = positionx2 - wheelbasewidth2 / 2;
            wheelposlby2 = positiony2 - wheelbaselength2 / 2;

            worldwheelrf2 = Matrix.CreateScale((float)(tyrewidthf2 / 0.22), (float)(wheelradiusfront2 / 0.3), (float)(wheelradiusfront2 / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationZ((float)(Math.PI)) * Matrix.CreateRotationX((float)(-tyredistance2 / wheelradiusfront2)) * Matrix.CreateTranslation(new Vector3((float)wheelposrfx2, (float)wheelposrfy2, (float)(wheelradiusfront2)));  //apply
            worldwheellf2 = Matrix.CreateScale((float)(tyrewidthf2 / 0.22), (float)(wheelradiusfront2 / 0.3), (float)(wheelradiusfront2 / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationX((float)(-tyredistance2 / wheelradiusfront2)) * Matrix.CreateTranslation(new Vector3((float)wheelposlfx2, (float)wheelposlfy2, (float)(wheelradiusfront2)));  //apply
            worldwheelrb2 = Matrix.CreateScale((float)(tyrewidthr2 / 0.22), (float)(wheelradiusrear2 / 0.3), (float)(wheelradiusrear2 / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationZ((float)(Math.PI)) * Matrix.CreateRotationX((float)(-tyredistance2 / wheelradiusrear2)) * Matrix.CreateTranslation(new Vector3((float)wheelposrbx2, (float)wheelposrby2, (float)(wheelradiusrear2)));  //apply 
            worldwheellb2 = Matrix.CreateScale((float)(tyrewidthr2 / 0.22), (float)(wheelradiusrear2 / 0.3), (float)(wheelradiusrear2 / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationX((float)(-tyredistance2 / wheelradiusrear2)) * Matrix.CreateTranslation(new Vector3((float)wheelposlbx2, (float)wheelposlby2, (float)(wheelradiusrear2)));  //apply
            //worldspringrf = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposrfx - tyrewidthf * dy / 2), (float)(wheelposrfy + tyrewidthf * dx / 2), (float)(wheelposrfz + 0.7)));  //apply
            //worldspringlf = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposlfx + tyrewidthf * dy / 2), (float)(wheelposlfy - tyrewidthf * dx / 2), (float)(wheelposlfz + 0.7)));  //apply
            //worldspringrb = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposrbx - tyrewidthr * dy / 2), (float)(wheelposrby + tyrewidthr * dx / 2), (float)(wheelposrbz + 0.7)));  //apply 
            //worldspringlb = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposlbx + tyrewidthr * dy / 2), (float)(wheelposlby - tyrewidthr * dx / 2), (float)(wheelposlbz + 0.7)));  //apply
            world02 = Matrix.CreateTranslation(0, 0, 0) * Matrix.CreateRotationX((float)(xangle2)) * Matrix.CreateTranslation((float)(positionx2), (float)(positiony2 + offsetlength2), (float)(positionz2 + (springrfpos2 + springrbpos2 + springlfpos2 + springlbpos2) / 4 + offsetheight2));

            pause5 = pause5 + 1;
        }

        public void getengineparam2()
        {
            a = rpm;
            rpm = rpm2;
            if (rpm <= 250)
            {
                lrpm = rpm02;
                urpm = rpm2502;
                arpm = 0;
            }
            else if (rpm <= 500)
            {
                lrpm = rpm2502;
                urpm = rpm5002;
                arpm = 250;
            }
            else if (rpm <= 750)
            {
                lrpm = rpm5002;
                urpm = rpm7502;
                arpm = 500;
            }
            else if (rpm <= 1000)
            {
                lrpm = rpm7502;
                urpm = rpm10002;
                arpm = 750;
            }
            else if (rpm <= 1250)
            {
                lrpm = rpm10002;
                urpm = rpm12502;
                arpm = 1000;
            }
            else if (rpm <= 1500)
            {
                lrpm = rpm12502;
                urpm = rpm15002;
                arpm = 1250;
            }
            else if (rpm <= 1750)
            {
                lrpm = rpm15002;
                urpm = rpm17502;
                arpm = 1500;
            }
            else if (rpm <= 2000)
            {
                lrpm = rpm17502;
                urpm = rpm20002;
                arpm = 1750;
            }
            else if (rpm <= 2250)
            {
                lrpm = rpm20002;
                urpm = rpm22502;
                arpm = 2000;
            }
            else if (rpm <= 2500)
            {
                lrpm = rpm22502;
                urpm = rpm25002;
                arpm = 2250;
            }
            else if (rpm <= 2750)
            {
                lrpm = rpm25002;
                urpm = rpm27502;
                arpm = 2500;
            }
            else if (rpm <= 3000)
            {
                lrpm = rpm27502;
                urpm = rpm30002;
                arpm = 2750;
            }
            else if (rpm <= 3250)
            {
                lrpm = rpm30002;
                urpm = rpm32502;
                arpm = 3000;
            }
            else if (rpm <= 3500)                  // engine data
            {
                lrpm = rpm32502;
                urpm = rpm35002;
                arpm = 3250;
            }
            else if (rpm <= 3750)
            {
                lrpm = rpm35002;
                urpm = rpm37502;
                arpm = 3500;
            }
            else if (rpm <= 4000)
            {
                lrpm = rpm37502;
                urpm = rpm40002;
                arpm = 3750;
            }
            else if (rpm <= 4250)
            {
                lrpm = rpm40002;
                urpm = rpm42502;
                arpm = 4000;
            }
            else if (rpm <= 4500)
            {
                lrpm = rpm42502;
                urpm = rpm45002;
                arpm = 4250;
            }
            else if (rpm <= 4750)
            {
                lrpm = rpm45002;
                urpm = rpm47502;
                arpm = 4500;
            }
            else if (rpm <= 5000)
            {
                lrpm = rpm47502;
                urpm = rpm50002;
                arpm = 4750;
            }
            else if (rpm <= 5250)
            {
                lrpm = rpm50002;
                urpm = rpm52502;
                arpm = 5000;
            }
            else if (rpm <= 5500)
            {
                lrpm = rpm52502;
                urpm = rpm55002;
                arpm = 5250;
            }
            else if (rpm <= 5750)
            {
                lrpm = rpm55002;
                urpm = rpm57502;
                arpm = 5500;
            }
            else if (rpm <= 6000)
            {
                lrpm = rpm57502;
                urpm = rpm60002;
                arpm = 5750;
            }
            else if (rpm <= 6250)
            {
                lrpm = rpm60002;
                urpm = rpm62502;
                arpm = 6000;
            }
            else if (rpm <= 6500)
            {
                lrpm = rpm62502;
                urpm = rpm65002;
                arpm = 6250;
            }
            else if (rpm <= 6750)
            {
                lrpm = rpm65002;
                urpm = rpm67502;
                arpm = 6500;
            }
            else if (rpm <= 7000)
            {
                lrpm = rpm67502;
                urpm = rpm70002;
                arpm = 6750;
            }
            else if (rpm <= 7250)
            {
                lrpm = rpm70002;
                urpm = rpm72502;
                arpm = 7000;
            }
            else if (rpm <= 7500)
            {
                lrpm = rpm72502;
                urpm = rpm75002;
                arpm = 7250;
            }
            else if (rpm <= 7750)
            {
                lrpm = rpm75002;
                urpm = rpm77502;
                arpm = 7500;
            }
            else if (rpm <= 8000)
            {
                lrpm = rpm77502;
                urpm = rpm80002;
                arpm = 7750;
            }
            else if (rpm <= 8250)
            {
                lrpm = rpm80002;
                urpm = rpm82502;
                arpm = 8000;
            }
            else if (rpm <= 8500)
            {
                lrpm = rpm82502;
                urpm = rpm85002;
                arpm = 8250;
            }
            else if (rpm <= 8500)
            {
                lrpm = rpm85002;
                urpm = rpm82502;
                arpm = 8500;
            }
            rpm = a;
        }


        public void getengineparam()
        {
            if (rpm <= 250)
            {
                lrpm = rpm0;
                urpm = rpm250;
                arpm = 0;
            }
            else if (rpm <= 500)
            {
                lrpm = rpm250;
                urpm = rpm500;
                arpm = 250;
            }
            else if (rpm <= 750)
            {
                lrpm = rpm500;
                urpm = rpm750;
                arpm = 500;
            }
            else if (rpm <= 1000)
            {
                lrpm = rpm750;
                urpm = rpm1000;
                arpm = 750;
            }
            else if (rpm <= 1250)
            {
                lrpm = rpm1000;
                urpm = rpm1250;
                arpm = 1000;
            }
            else if (rpm <= 1500)
            {
                lrpm = rpm1250;
                urpm = rpm1500;
                arpm = 1250;
            }
            else if (rpm <= 1750)
            {
                lrpm = rpm1500;
                urpm = rpm1750;
                arpm = 1500;
            }
            else if (rpm <= 2000)
            {
                lrpm = rpm1750;
                urpm = rpm2000;
                arpm = 1750;
            }
            else if (rpm <= 2250)
            {
                lrpm = rpm2000;
                urpm = rpm2250;
                arpm = 2000;
            }
            else if (rpm <= 2500)
            {
                lrpm = rpm2250;
                urpm = rpm2500;
                arpm = 2250;
            }
            else if (rpm <= 2750)
            {
                lrpm = rpm2500;
                urpm = rpm2750;
                arpm = 2500;
            }
            else if (rpm <= 3000)
            {
                lrpm = rpm2750;
                urpm = rpm3000;
                arpm = 2750;
            }
            else if (rpm <= 3250)
            {
                lrpm = rpm3000;
                urpm = rpm3250;
                arpm = 3000;
            }
            else if (rpm <= 3500)                  // engine data
            {
                lrpm = rpm3250;
                urpm = rpm3500;
                arpm = 3250;
            }
            else if (rpm <= 3750)
            {
                lrpm = rpm3500;
                urpm = rpm3750;
                arpm = 3500;
            }
            else if (rpm <= 4000)
            {
                lrpm = rpm3750;
                urpm = rpm4000;
                arpm = 3750;
            }
            else if (rpm <= 4250)
            {
                lrpm = rpm4000;
                urpm = rpm4250;
                arpm = 4000;
            }
            else if (rpm <= 4500)
            {
                lrpm = rpm4250;
                urpm = rpm4500;
                arpm = 4250;
            }
            else if (rpm <= 4750)
            {
                lrpm = rpm4500;
                urpm = rpm4750;
                arpm = 4500;
            }
            else if (rpm <= 5000)
            {
                lrpm = rpm4750;
                urpm = rpm5000;
                arpm = 4750;
            }
            else if (rpm <= 5250)
            {
                lrpm = rpm5000;
                urpm = rpm5250;
                arpm = 5000;
            }
            else if (rpm <= 5500)
            {
                lrpm = rpm5250;
                urpm = rpm5500;
                arpm = 5250;
            }
            else if (rpm <= 5750)
            {
                lrpm = rpm5500;
                urpm = rpm5750;
                arpm = 5500;
            }
            else if (rpm <= 6000)
            {
                lrpm = rpm5750;
                urpm = rpm6000;
                arpm = 5750;
            }
            else if (rpm <= 6250)
            {
                lrpm = rpm6000;
                urpm = rpm6250;
                arpm = 6000;
            }
            else if (rpm <= 6500)
            {
                lrpm = rpm6250;
                urpm = rpm6500;
                arpm = 6250;
            }
            else if (rpm <= 6750)
            {
                lrpm = rpm6500;
                urpm = rpm6750;
                arpm = 6500;
            }
            else if (rpm <= 7000)
            {
                lrpm = rpm6750;
                urpm = rpm7000;
                arpm = 6750;
            }
            else if (rpm <= 7250)
            {
                lrpm = rpm7000;
                urpm = rpm7250;
                arpm = 7000;
            }
            else if (rpm <= 7500)
            {
                lrpm = rpm7250;
                urpm = rpm7500;
                arpm = 7250;
            }
            else if (rpm <= 7750)
            {
                lrpm = rpm7500;
                urpm = rpm7750;
                arpm = 7500;
            }
            else if (rpm <= 8000)
            {
                lrpm = rpm7750;
                urpm = rpm8000;
                arpm = 7750;
            }
            else if (rpm <= 8250)
            {
                lrpm = rpm8000;
                urpm = rpm8250;
                arpm = 8000;
            }
            else if (rpm <= 8500)
            {
                lrpm = rpm8250;
                urpm = rpm8500;
                arpm = 8250;
            }
            else if (rpm <= 8500)
            {
                lrpm = rpm8500;
                urpm = rpm8250;
                arpm = 8500;
            }
        }


        public void newcustomvehicle()
        {
            model = Content.Load<Model>(currentcustomvehicle.model);
            collisionmodel = Content.Load<Model>(currentcustomvehicle.collisionmodel);
            wheelfront = Content.Load<Model>(currentcustomvehicle.wheelfront);
            wheelrear = Content.Load<Model>(currentcustomvehicle.wheelrear);
            wheelradiusfront = currentcustomvehicle.wheelradiusfront;
            wheelradiusrear = currentcustomvehicle.wheelradiusrear;
            offsetlength = currentcustomvehicle.offsetlength;
            offsetheight = currentcustomvehicle.offsetheight;
            mass = currentcustomvehicle.mass;
            frontwheeldrive = currentcustomvehicle.frontwheeldrive;
            wheelbasewidth = currentcustomvehicle.wheelbasewidth;
            wheelbaselength = currentcustomvehicle.wheelbaselength;
            massheight = currentcustomvehicle.massheight;
            masswidth = currentcustomvehicle.masswidth;
            masslength = currentcustomvehicle.masslength;
            frontweight = currentcustomvehicle.frontweight;
            springstiffnessf = currentcustomvehicle.springstiffnessf;
            springstiffnessb = currentcustomvehicle.springstiffnessb;
            springdampingf = currentcustomvehicle.springdampingf;
            springdampingb = currentcustomvehicle.springdampingb;
            gears = currentcustomvehicle.gears;
            for (int i = 0; i < gears + 2; i++)
            {
                ratiovector[i] = currentcustomvehicle.ratiovector[i];
            }
            finaldriveratio = currentcustomvehicle.finaldriveratio;
            shiftingtime = currentcustomvehicle.shiftingtime;
            idlerpm = currentcustomvehicle.idlerpm;
            maxrpm = currentcustomvehicle.maxrpm;
            launchrpm = currentcustomvehicle.launchrpm;
            Tyretype = currentcustomvehicle.Tyretype;      //normal = 4.3-4.7 sport = 4.7-5 drag radials = 5.1 slicks = 5.3+
            tyrewidthf = currentcustomvehicle.tyrewidthf;  // 0.22 base(m)
            tyrewidthr = currentcustomvehicle.tyrewidthr;  // 0.22 base(m)
            Cv = currentcustomvehicle.Cv;
            frontalarea = currentcustomvehicle.frontalarea;
            displacement = currentcustomvehicle.displacement;
            friction = currentcustomvehicle.friction;
            rpm0 = currentcustomvehicle.rpm0;
            compression = currentcustomvehicle.compression;
            enginetype = currentcustomvehicle.enginetype;
            fuel = currentcustomvehicle.fuel;
            airfuelratio = currentcustomvehicle.airfuelratio;
            info = currentcustomvehicle.info;
            h1 = currentcustomvehicle.h1;
            h2 = currentcustomvehicle.h2;
            h3 = currentcustomvehicle.h3;
            h4 = currentcustomvehicle.h4;
            rpm250 = currentcustomvehicle.rpm250;
            rpm500 = currentcustomvehicle.rpm500;
            rpm750 = currentcustomvehicle.rpm750;
            rpm1000 = currentcustomvehicle.rpm1000;
            rpm1250 = currentcustomvehicle.rpm1250;
            rpm1500 = currentcustomvehicle.rpm1500;
            rpm1750 = currentcustomvehicle.rpm1750;
            rpm2000 = currentcustomvehicle.rpm2000;
            rpm2250 = currentcustomvehicle.rpm2250;
            rpm2500 = currentcustomvehicle.rpm2500;
            rpm2750 = currentcustomvehicle.rpm2750;
            rpm3000 = currentcustomvehicle.rpm3000;
            rpm3250 = currentcustomvehicle.rpm3250;
            rpm3500 = currentcustomvehicle.rpm3500;
            rpm3750 = currentcustomvehicle.rpm3750;
            rpm4000 = currentcustomvehicle.rpm4000;
            rpm4250 = currentcustomvehicle.rpm4250;
            rpm4500 = currentcustomvehicle.rpm4500;
            rpm4750 = currentcustomvehicle.rpm4750;
            rpm5000 = currentcustomvehicle.rpm5000;
            rpm5250 = currentcustomvehicle.rpm5250;
            rpm5500 = currentcustomvehicle.rpm5500;
            rpm5750 = currentcustomvehicle.rpm5750;
            rpm6000 = currentcustomvehicle.rpm6000;
            rpm6250 = currentcustomvehicle.rpm6250;
            rpm6500 = currentcustomvehicle.rpm6500;
            rpm6750 = currentcustomvehicle.rpm6750;
            rpm7000 = currentcustomvehicle.rpm7000;
            rpm7250 = currentcustomvehicle.rpm7250;
            rpm7500 = currentcustomvehicle.rpm7500;
            rpm7750 = currentcustomvehicle.rpm7750;
            rpm8000 = currentcustomvehicle.rpm8000;
            rpm8250 = currentcustomvehicle.rpm8250;
            rpm8500 = currentcustomvehicle.rpm8500;
            rpm8750 = currentcustomvehicle.rpm8750;
            rpm9000 = currentcustomvehicle.rpm9000;


            rpm = idlerpm;
            gear = 2;
            ratio = ratiovector[2] / (wheelradiusfront * frontwheeldrive + wheelradiusrear * (1 - frontwheeldrive)) * finaldriveratio;
            momentofinertia = mass * Math.Pow((masswidth + masslength), 2) / 12;
        }

        public void newpart()
        {
            if (currentpart.type == "injectors")
            {
                injectorsize = currentpart.value1 * cylinders;
            }
            if (currentpart.type == "exhaust")
            {
                exhaust = true;
                sportexhaust = false;
                racingexhaust = false;
                exhaustmax = Math.Pow(currentpart.value1 * 2.54 / 2,2) * 50 / 2.119;    // 2.119: convert from cfm to liter/sec
            }
            if (currentpart.type == "sportexhaust")
            {
                sportexhaust = true;
                racingexhaust = false;
                exhaustmax = Math.Pow(currentpart.value1 * 2.54 / 2, 2) * 50 / 2.119;    // 2.119: convert from cfm to liter/sec
            }
            if (currentpart.type == "racingexhaust")
            {
                racingexhaust = true;
                exhaust = false;
                sportexhaust = false;
                exhaustmax = Math.Pow(currentpart.value1 * 2.54 / 2, 2) * 50 / 2.119;    // 2.119: convert from cfm to liter/sec
            }
            if (currentpart.type == "cai")
                cai = true;
            if (currentpart.type == "port heads")
                ported = true;
            if (currentpart.type == "racingmanifold")
                racingmanifold = true;
            if (currentpart.type == "turboconversion" & turbo == false)
            {
                turbo = true;
                supercharger = false;
            }
            if (currentpart.type == "turbo" & turbo)
            {
                a = turbosize;
                turbosize = currentpart.value1;
                turbomax = currentpart.value2;
                mass = mass + turbosize / 1.5 + 30 - a / 1.5 - 30;
                twinturbo = false;
            }
            if (currentpart.type == "twinturbo" & turbo)
            {
                a = turbosize;
                turbosize = currentpart.value1;
                turbomax = currentpart.value2;
                mass = mass + turbosize / 1.5 + 30 - a / 1.5 - 30;
                twinturbo = true;
            }
            if (currentpart.type == "superchargerconversion" & supercharger == false)
            {
                turbo = false;
                supercharger = true;
            }
            if (currentpart.type == "supercharger" & supercharger)
            {
                a = turbosize;
                turbosize = currentpart.value1;
                turbomax = currentpart.value2;
                mass = mass + turbosize / 1.5 + 30 - a / 1.5 - 30;
            }
            if (currentpart.type == "nos")
            {
                turbomax = currentpart.value1;
                turbosize = currentpart.value2;
                nos = true;
            }
            if (currentpart.type == "ecutune" & ecu == false)
            {
                if (airfuelratio > 13.5 & fuel == "petrol")
                    airfuelratio = 13.5;
                else if (airfuelratio > 14 & fuel == "diesel")
                    airfuelratio = airfuelratio * 0.9;
                if (airfuelratio < 14 & fuel == "diesel")
                    airfuelratio = 14;
                enginerestriction.X = 0;
                enginerestriction.Y = 0;
                enginerestriction.Z = 0;
                ecu = true;
            }
            if (currentpart.type == "customecu" & customecu == false)
            {
                if (airfuelratio > 12.5 & fuel == "petrol")
                    airfuelratio = 12.5;
                else if (airfuelratio > 14 & fuel == "diesel")
                    airfuelratio = airfuelratio * 0.9;
                if (airfuelratio < 14 & fuel == "diesel")
                    airfuelratio = 14;
                enginerestriction.X = 0;
                enginerestriction.Y = 0;
                enginerestriction.Z = 0;
                customecu = true;
            }
            if (currentpart.type == "roadtyre")
            {
                Tyretype.X = (float)currentpart.value1;
                Tyretype.Y = (float)currentpart.value2;
                Tyretype.Z = 2;
                Tyretype.W = 1;
                tyrewidthf = currentpart.value3;
                tyrewidthr = currentpart.value4;
            }
            if (currentpart.type == "mixtyre")
            {
                Tyretype.X = (float)currentpart.value1;
                Tyretype.Y = (float)currentpart.value2;
                Tyretype.Z = 2.5f;
                Tyretype.W = 1.5f;
                tyrewidthf = currentpart.value3;
                tyrewidthr = currentpart.value4;
            }
            if (currentpart.type == "wettyre")
            {
                Tyretype.Y = (float)currentpart.value1;
                Tyretype.Z = (float)currentpart.value2;
                Tyretype.X = 4.6f;
                Tyretype.W = 1.5f;
                tyrewidthf = currentpart.value3;
                tyrewidthr = currentpart.value4;
            }
            if (currentpart.type == "snowtyre")
            {
                Tyretype.X = (float)currentpart.value1;
                Tyretype.W = (float)currentpart.value2;
                Tyretype.Y = 2.5f;
                Tyretype.Z = 2;
                tyrewidthf = currentpart.value3;
                tyrewidthr = currentpart.value4;
            }
            if (currentpart.type == "camshafts")
            {
                camangle = (float)currentpart.value1;
            }
            if (currentpart.type == "racing valvesprings" & valvesprings == false)
            {
                camlift = camlift + 700;
                valvesprings = true;
            }
            if (currentpart.type == "racing valves" & valves == false)
            {
                camlift = camlift + 700;
                valves = true;
            }
            if (currentpart.type == "solid camlobes" & camlobes == false)
            {
                camlift = camlift + 700;
                camlobes = true;
            }
            if (camlobes & valves & valvesprings & camlift < 9000)
                camlift = 9000;
            if (currentpart.type == "suspension")
            {
                springstiffnessf = (float)currentpart.value1;
                springstiffnessb = (float)currentpart.value2;
            }
            if (currentpart.type == "gearbox")
            {
                springstiffnessf = (float)currentpart.value1;
                springstiffnessb = (float)currentpart.value2;
            }
        }

        public void newopponent()
        {
            model2 = Content.Load<Model>(currentvehicle.model);
            wheelfront2 = Content.Load<Model>(currentvehicle.wheelfront);
            wheelrear2 = Content.Load<Model>(currentvehicle.wheelrear);
            wheelfront2 = Content.Load<Model>(currentvehicle.wheelfront);
            wheelrear2 = Content.Load<Model>(currentvehicle.wheelrear);
            wheelradiusfront2 = currentvehicle.wheelradiusfront;
            wheelradiusrear2 = currentvehicle.wheelradiusrear;
            offsetlength2 = currentvehicle.offsetlength;
            offsetheight2 = currentvehicle.offsetheight;
            mass2 = currentvehicle.mass;
            frontwheeldrive2 = currentvehicle.frontwheeldrive;
            wheelbasewidth2 = currentvehicle.wheelbasewidth;
            wheelbaselength2 = currentvehicle.wheelbaselength;
            massheight2 = currentvehicle.massheight;
            frontweight2 = currentvehicle.frontweight;
            springstiffnessf2 = currentvehicle.springstiffnessf;
            springstiffnessb2 = currentvehicle.springstiffnessb;
            springdampingf2 = currentvehicle.springdampingf;
            springdampingb2 = currentvehicle.springdampingb;
            gears2 = currentvehicle.gears;
            for (int i = 0; i < gears2 + 2; i++)
            {
                ratiovector2[i] = currentvehicle.ratiovector[i];
            }
            finaldriveratio2 = currentvehicle.finaldriveratio;
            shiftingtime2 = currentvehicle.shiftingtime;
            maxrpm2 = currentvehicle.maxrpm;
            launchrpm2 = currentvehicle.launchrpm;
            Tyretype2 = currentvehicle.Tyretype;      //normal =
            tyrebasegrip2 = Tyretype2.X;
            tyrewidthf2 = currentvehicle.tyrewidthf;  // 0.22 base(m)
            tyrewidthr2 = currentvehicle.tyrewidthr;  // 0.22 base(m)
            Cv2 = currentvehicle.Cv;
            frontalarea2 = currentvehicle.frontalarea;
            displacement2 = currentvehicle.displacement;
            turbosize2 = currentvehicle.turbosize;
            camangle2 = currentvehicle.camangle;
            camlift2 = currentvehicle.camlift;
            friction2 = currentvehicle.friction;
            compression2 = currentvehicle.compression;
            airfuelratio2 = currentvehicle.airfuelratio;
            enginerestriction2 = currentvehicle.enginerestriction;
            turbo2 = currentvehicle.turbo;
            twinturbo2 = currentvehicle.twinturbo;
            supercharger2 = currentvehicle.supercharger;
            stroketype2 = currentvehicle.stroketype;
            stroke2 = currentvehicle.stroke;
            exhaust2 = currentvehicle.exhaust;
            sportexhaust2 = currentvehicle.sportexhaust;
            racingexhaust2 = currentvehicle.racingexhaust;
            cai2 = currentvehicle.cai;
            racingmanifold2 = currentvehicle.racingmanifold;


            currentengine = Content.Load<engine>(currentvehicle.engine);   // load engine file

            fuel2 = currentengine.fuel;
            peakve2 = currentengine.peakve;
            rpm02 = currentengine.rpm0;
            rpm2502 = currentengine.rpm250;
            rpm5002 = currentengine.rpm500;
            rpm7502 = currentengine.rpm750;
            rpm10002 = currentengine.rpm1000;
            rpm12502 = currentengine.rpm1250;
            rpm15002 = currentengine.rpm1500;
            rpm17502 = currentengine.rpm1750;
            rpm20002 = currentengine.rpm2000;
            rpm22502 = currentengine.rpm2250;
            rpm25002 = currentengine.rpm2500;
            rpm27502 = currentengine.rpm2750;
            rpm30002 = currentengine.rpm3000;
            rpm32502 = currentengine.rpm3250;
            rpm35002 = currentengine.rpm3500;
            rpm37502 = currentengine.rpm3750;
            rpm40002 = currentengine.rpm4000;
            rpm42502 = currentengine.rpm4250;
            rpm45002 = currentengine.rpm4500;
            rpm47502 = currentengine.rpm4750;
            rpm50002 = currentengine.rpm5000;
            rpm52502 = currentengine.rpm5250;
            rpm55002 = currentengine.rpm5500;
            rpm57502 = currentengine.rpm5750;
            rpm60002 = currentengine.rpm6000;
            rpm62502 = currentengine.rpm6250;
            rpm65002 = currentengine.rpm6500;
            rpm67502 = currentengine.rpm6750;
            rpm70002 = currentengine.rpm7000;
            rpm72502 = currentengine.rpm7250;
            rpm75002 = currentengine.rpm7500;
            rpm77502 = currentengine.rpm7750;
            rpm80002 = currentengine.rpm8000;
            rpm82502 = currentengine.rpm8250;
            rpm85002 = currentengine.rpm8500;
            rpm87502 = currentengine.rpm8750;
            rpm90002 = currentengine.rpm9000;

            if (currentvehicle.exhaustdiameter == 0 & turbo2 == false & supercharger2 == false & rpm6500.X < 0.8)
                exhaustmax2 = peakve2 * (5000 + camangle2) / 60 * displacement2 / 1000 / stroketype2 * 1.45 * 1.2;                 // auto generates an exhaust   1.2/1.4 is margin
            else if (currentvehicle.exhaustdiameter == 0 & turbo2 == false & supercharger2 == false & rpm7750.X < 0.8)
                exhaustmax2 = peakve2 * (5000 + camangle2) / 60 * displacement2 / 1000 / stroketype2 * 1.45 * 1.5;
            else if (currentvehicle.exhaustdiameter == 0 & turbo2 == false & supercharger2 == false)
                exhaustmax2 = peakve2 * (5000 + camangle2) / 60 * displacement2 / 1000 / stroketype2 * 1.45 * 1.8;
            else if (currentvehicle.exhaustdiameter == 0)
                exhaustmax2 = peakve2 * 1.8 * (5000 + camangle2) / 60 * displacement2 / 1000 / stroketype2 * 1.45 * 1.3;  // asume 0.8bar boost 
            else
                exhaustmax2 = Math.Pow(currentvehicle.exhaustdiameter * 2.54 / 2, 2) * 50 / 2.119;     // calculated when exhaustdiameter is provided

            if (turbo2 == false & supercharger2 == false & rpm6500.X < 0.8)
                injectorsize2 = peakve2 * (5000 + camangle2) * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771 * 1.3;  //    volume m3 per min(air) / fuelratio * weight per m3(air) / weight per liter(fuel) = cc per min    1.4/1.7 is just to have some margin
            else if (turbo2 == false & supercharger2 == false & rpm7750.X < 0.8)
                injectorsize2 = peakve2 * (5000 + camangle2) * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771 * 1.6;
            else if (turbo2 == false & supercharger2 == false)
                injectorsize2 = peakve2 * (5000 + camangle2) * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771 * 1.8;
            else
                injectorsize2 = peakve2 * 1.8 * (5000 + camangle2) * displacement2 / 1000 / stroketype2 / airfuelratio2 * 1.2 / 0.771 * 1.3;   // asume 0.8 bar boost


            wheelmoif2 = 2 * tyrewidthf2 * wheelradiusfront2 * 150 * Math.Pow(wheelradiusfront2, 2);
            wheelmoir2 = 2 * tyrewidthr2 * wheelradiusrear2 * 150 * Math.Pow(wheelradiusrear2, 2);
            rpm2 = launchrpm2;
            gear2 = 2;
            ratio2 = ratiovector2[2] / (wheelradiusfront2 * frontwheeldrive2 + wheelradiusrear2 * (1 - frontwheeldrive2)) * finaldriveratio2;
        }

        public void newvehicle()
        {
            model = Content.Load<Model>(currentvehicle.model);
            collisionmodel = Content.Load<Model>(currentvehicle.collisionmodel);
            wheelfront = Content.Load<Model>(currentvehicle.wheelfront);
            wheelrear = Content.Load<Model>(currentvehicle.wheelrear);
            wheelradiusfront = currentvehicle.wheelradiusfront;
            wheelradiusrear = currentvehicle.wheelradiusrear;
            offsetlength = currentvehicle.offsetlength;
            offsetheight = currentvehicle.offsetheight;
            mass = currentvehicle.mass;
            frontwheeldrive = currentvehicle.frontwheeldrive;
            wheelbasewidth = currentvehicle.wheelbasewidth;
            wheelbaselength = currentvehicle.wheelbaselength;
            massheight = currentvehicle.massheight;
            masswidth = currentvehicle.masswidth;
            masslength = currentvehicle.masslength;
            frontweight = currentvehicle.frontweight;
            springstiffnessf = currentvehicle.springstiffnessf;
            springstiffnessb = currentvehicle.springstiffnessb;
            springdampingf = currentvehicle.springdampingf;
            springdampingb = currentvehicle.springdampingb;
            gears = currentvehicle.gears;
            for (int i = 0; i < gears + 2; i++)
            {
                ratiovector[i] = currentvehicle.ratiovector[i];
            }
            finaldriveratio = currentvehicle.finaldriveratio;
            shiftingtime = currentvehicle.shiftingtime;
            idlerpm = currentvehicle.idlerpm;
            maxrpm = currentvehicle.maxrpm;
            launchrpm = currentvehicle.launchrpm;
            Tyretype = currentvehicle.Tyretype;      //normal = 4.3-4.7 sport = 4.7-5 drag radials = 5.1 slicks = 5.3+
            tyrewidthf = currentvehicle.tyrewidthf;  // 0.22 base(m)
            tyrewidthr = currentvehicle.tyrewidthr;  // 0.22 base(m)
            Cv = currentvehicle.Cv;
            frontalarea = currentvehicle.frontalarea;
            displacement = currentvehicle.displacement;
            turbosize = currentvehicle.turbosize;
            turbomax = currentvehicle.turbomax;
            camangle = currentvehicle.camangle;
            camlift = currentvehicle.camlift;
            friction = currentvehicle.friction;
            compression = currentvehicle.compression;
            airfuelratio = currentvehicle.airfuelratio;
            camerapos = currentvehicle.camerapos;
            enginerestriction = currentvehicle.enginerestriction;
            turningradius = currentvehicle.turningradius;
            turbo = currentvehicle.turbo;
            twinturbo = currentvehicle.twinturbo;
            supercharger = currentvehicle.supercharger;
            cylinders = currentvehicle.cylinders;
            stroketype = currentvehicle.stroketype;
            stroke = currentvehicle.stroke;
            exhaust = currentvehicle.exhaust;
            sportexhaust = currentvehicle.sportexhaust;
            racingexhaust = currentvehicle.racingexhaust;
            cai = currentvehicle.cai;
            racingmanifold = currentvehicle.racingmanifold;

            currentengine = Content.Load<engine>(currentvehicle.engine);   // load engine file
        
            enginetype = currentengine.enginetype;
            fuel = currentengine.fuel;
            info = currentvehicle.info;
            h1 = currentengine.h1;
            h2 = currentengine.h2;
            h3 = currentengine.h3;
            h4 = currentengine.h4;
            peakve = currentengine.peakve;
            rpm0 = currentengine.rpm0;
            rpm250 = currentengine.rpm250;
            rpm500 = currentengine.rpm500;
            rpm750 = currentengine.rpm750;
            rpm1000 = currentengine.rpm1000;
            rpm1250 = currentengine.rpm1250;
            rpm1500 = currentengine.rpm1500;
            rpm1750 = currentengine.rpm1750;
            rpm2000 = currentengine.rpm2000;
            rpm2250 = currentengine.rpm2250;
            rpm2500 = currentengine.rpm2500;
            rpm2750 = currentengine.rpm2750;
            rpm3000 = currentengine.rpm3000;
            rpm3250 = currentengine.rpm3250;
            rpm3500 = currentengine.rpm3500;
            rpm3750 = currentengine.rpm3750;
            rpm4000 = currentengine.rpm4000;
            rpm4250 = currentengine.rpm4250;
            rpm4500 = currentengine.rpm4500;
            rpm4750 = currentengine.rpm4750;
            rpm5000 = currentengine.rpm5000;
            rpm5250 = currentengine.rpm5250;
            rpm5500 = currentengine.rpm5500;
            rpm5750 = currentengine.rpm5750;
            rpm6000 = currentengine.rpm6000;
            rpm6250 = currentengine.rpm6250;
            rpm6500 = currentengine.rpm6500;
            rpm6750 = currentengine.rpm6750;
            rpm7000 = currentengine.rpm7000;
            rpm7250 = currentengine.rpm7250;
            rpm7500 = currentengine.rpm7500;
            rpm7750 = currentengine.rpm7750;
            rpm8000 = currentengine.rpm8000;
            rpm8250 = currentengine.rpm8250;
            rpm8500 = currentengine.rpm8500;
            rpm8750 = currentengine.rpm8750;
            rpm9000 = currentengine.rpm9000;

                             // do some calculations

            bore = Math.Pow(displacement / Math.PI * 4 / stroke / 1000 / cylinders, 0.5) * 1000; 


            if (currentvehicle.exhaustdiameter == 0 & turbo == false & supercharger == false & rpm6500.X < 0.8)
                exhaustmax = peakve * (5000 + camangle) / 60 * displacement / 1000 / stroketype * 1.45 * 1.2;                 // auto generates an exhaust   1.2/1.4 is margin
            else if (currentvehicle.exhaustdiameter == 0 & turbo == false & supercharger == false & rpm7750.X < 0.8)
                exhaustmax = peakve * (5000 + camangle) / 60 * displacement / 1000 / stroketype * 1.45 * 1.5;
            else if (currentvehicle.exhaustdiameter == 0 & turbo == false & supercharger == false)
                exhaustmax = peakve * (5000 + camangle) / 60 * displacement / 1000 / stroketype * 1.45 * 1.8;  
            else if (currentvehicle.exhaustdiameter == 0)
                exhaustmax = peakve * 1.8 * (5000 + camangle) / 60 * displacement / 1000 / stroketype * 1.45 * 1.3;  // asume 0.8bar boost 
            else
                exhaustmax = Math.Pow(currentvehicle.exhaustdiameter * 2.54 / 2, 2) * 50 / 2.119;     // calculated when exhaustdiameter is provided

            if (turbo == false & supercharger == false & rpm6500.X < 0.8)
                injectorsize = peakve * (5000 + camangle) * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 * 1.3;  //    volume m3 per min(air) / fuelratio * weight per m3(air) / weight per liter(fuel) = cc per min    1.4/1.7 is just to have some margin
            else if (turbo == false & supercharger == false & rpm7750.X < 0.8)
                injectorsize = peakve * (5000 + camangle) * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 * 1.6;
            else if (turbo == false & supercharger == false)
                injectorsize = peakve * (5000 + camangle) * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 * 1.8;
            else
                injectorsize = peakve * 1.8 * (5000 + camangle) * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 * 1.3;   // asume 0.8 bar boost


            wheelmoif = 2 * tyrewidthf * wheelradiusfront * 150 * Math.Pow(wheelradiusfront, 2);
            wheelmoir = 2 * tyrewidthr * wheelradiusrear * 150 * Math.Pow(wheelradiusrear, 2);
            rpm = idlerpm;
            gear = 2;
            ratio = ratiovector[2] / (wheelradiusfront * frontwheeldrive + wheelradiusrear * (1 - frontwheeldrive)) * finaldriveratio;
            momentofinertia = mass * Math.Pow((masswidth + masslength), 2) / 12;
            customecu = false;
            valvesprings = false;
            valves = false;
            camlobes = false;
            ported = false;
            waterinjection = false;
            methanolinjection = false;
            variablesparkplug = false;
            if (enginerestriction.Y > 0.4 & compression > 8.5)
                variablesparkplug = true;
            else if (compression > 10.9)
                variablesparkplug = true;
            raceintercooler = false;
            intercooler = false;
            if (enginerestriction.Y > 0.6)
                intercooler = true;
        }

        public void carshopcheck()
        {
            for (int i = 0; i < 6; i++)
            {
                carshopvector = new Vector3(carshoppositionx[i], carshoppositiony[i], carshoppositionz[i]);
                if (Distance2(carshopvector, positionvector) < 3 & stationary)
                {
                    currentcarshop = Content.Load<carshop>("carshops/" + Convert.ToString(i + 1,10));
                    for (int u = 0; u < 32; u++)
                    {
                        if (currentcarshop.type == "junkyard")
                            randomvector[u] = random.NextDouble();
                        else
                            randomvector[u] = 0;
                    }
                    menu = 3;
                }
                pause3 = 0;
            }
        }
        public void partshopcheck()
        {
            for (int i = 0; i < 2; i++)
            {
                partshopvector = new Vector3(partshoppositionx[i], partshoppositiony[i], partshoppositionz[i]);
                if (Distance2(partshopvector, positionvector) < 4 & stationary)
                {
                    currentpartshop = Content.Load<partshop>("partshops/" + Convert.ToString(i + 1, 10));
                    menu = 5;
                }
            }
        }
        public void dyno()
        {
            Array.Clear(torquevector, 0, (int)maxrpm / 10);
            Array.Clear(hpvector, 0, (int)maxrpm / 10);
            for (int i = 0; i < maxrpm / 10; i++)
            {
                rpm = i * 10;

                getengineparam();
                if (turbo == false & supercharger == false)
                    currentboost = 0;
                else
                    currentboost = lrpm.Y + (rpm - arpm) / 250 * (urpm.Y - lrpm.Y);    //extrapolation of engine parameters


                b = rpm;
                rpm = rpm - camangle;
                getengineparam();
                ve = lrpm.X + (rpm - arpm) / 250 * (urpm.X - lrpm.X);                  //extrapolation of engine parameters

                pistonacceleration = stroke / 2000 * Math.Pow(2 * Math.PI * b / 60, 2);
                
                if (sportexhaust)
                    ve = ve + 0.02;
                else if (racingexhaust)
                    ve = ve + 0.04;
                if (racingmanifold)
                    ve = ve + 0.03;
                if (cai)
                    ve = ve + 0.01;
                if (ported)
                    ve = ve + 0.02;
                if (racingexhaust & racingmanifold & cai & ported & peakve < 0.95)
                    ve = ve + 0.02;
                if (racingexhaust & racingmanifold & cai & ported & peakve < 1)
                    ve = ve + 0.01;
                
                if (currentboost > enginerestriction.Y & enginerestriction.Y != 0)
                    currentboost = enginerestriction.Y;


                if (fuel == "petrol")
                {
                    engineefficiency = 0.31 * Math.Pow(compression / 11, 0.2);
                    if (ve * rpm / 60 * displacement / 1000 / stroketype > intakemax)      //intake limitation
                        ve = intakemax * 1000 * stroketype * 60 / displacement / rpm;
                    if (enginerestriction.X < turbosize & enginerestriction.X != 0)        //ecu turbo cfm limitation
                        d = enginerestriction.X;
                    else
                        d = turbosize;
                    a = Math.Pow((d / 2), 2) * Math.PI / 3 * 0.95;  // a = cfm of turbo
                    if (twinturbo)
                        a = a * 0.85;
                    if ((ve + currentboost) * rpm / 60 * displacement / 1000 / stroketype > a / 2.119)  //convert cfm (a) to litre per sec
                        currentboost = a / 2.119 / rpm * 60 / displacement * 1000 * stroketype - ve;
                    if (currentboost < 0)
                        currentboost = 0;
                    if (currentboost > turbomax)
                        currentboost = turbomax;
                    if (ve * (1 + currentboost) * rpm / 60 * displacement / 1000 / stroketype * 1.45 > exhaustmax)
                        currentboost = exhaustmax * 1000 * stroketype * 60 / displacement / rpm / ve / 1.45 - 1;       //exhaust limitation     1.45: correcting factor for added fuel and exhaust temp
                    if (pistonacceleration > 22000)
                        engineefficiency = engineefficiency * Math.Pow(22000 / pistonacceleration, pistonweight / 1.5);          // piston acceleration
                    maxtorque = (ve * (currentboost + 1)) * displacement / 1000 / stroketype * 690 * engineefficiency;   //engine torque extrapolation from data               
                    maxtorque = maxtorque * Math.Pow(12.5 / airfuelratio, 0.3);
                    if (airfuelratio < 12.5)
                        maxtorque = maxtorque * (airfuelratio / 12.5);
                    if (maxtorque > enginerestriction.Z & enginerestriction.Z != 0)
                        maxtorque = enginerestriction.Z;

                    if (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 > injectorsize * 0.9)
                        maxtorque = maxtorque * 0.9 * injectorsize / (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771);

                    if (b > camlift)
                    {
                        maxtorque = maxtorque * Math.Pow(camlift / b,2.5);
                    }
                    if (b > camlift * 1.15)
                        maxtorque = 0;
     
                }
                if (fuel == "diesel")
                {
                    engineefficiency = 0.35 * Math.Pow(compression / 20, 0.2);
                    if (ve * rpm / 60 * displacement / 1000 / stroketype > intakemax)
                        ve = intakemax * 1000 * stroketype * 60 / displacement / rpm;       //intake limitation
                    if (enginerestriction.X < turbosize & enginerestriction.X != 0)
                        d = enginerestriction.X;
                    else
                        d = turbosize;
                    a = Math.Pow((d / 2), 2) * Math.PI / 3 * 0.95;  // a = cfm of turbo
                    if (twinturbo)
                        a = a * 0.85;
                    if ((ve + currentboost) * rpm / 60 * displacement / 1000 / stroketype > a / 2.119)
                        currentboost = a / 2.119 / rpm * 60 / displacement * 1000 * stroketype - ve;
                    if (currentboost < 0)
                        currentboost = 0;
                    if (currentboost > turbomax)
                        currentboost = turbomax;
                    if (ve * (1 + currentboost) * rpm / 60 * displacement / 1000 / stroketype * 1.45 > exhaustmax)
                        currentboost = exhaustmax * 1000 * stroketype * 60 / displacement / rpm / ve / 1.45 - 1;       //exhaust limitation     1.45: correcting factor for added fuel and exhaust temp
                    if (rpm > 3000)
                        engineefficiency = engineefficiency * Math.Pow(3000 / rpm, 0.6);   // because diesel is slow-burning
                    if (pistonacceleration > 22000)
                        engineefficiency = engineefficiency * Math.Pow(22000 / pistonacceleration, pistonweight / 1.5); //piston acceleration
                    maxtorque = (ve * (currentboost + 1)) * displacement / 1000 / stroketype * 690 * engineefficiency;   //engine torque extrapolation from data
                    maxtorque = maxtorque * Math.Pow(12.5 / airfuelratio, 0.5);
                    if (airfuelratio < 12.5)
                        maxtorque = maxtorque * (airfuelratio / 12.5);
                    if (maxtorque > enginerestriction.Z & enginerestriction.Z != 0)
                        maxtorque = enginerestriction.Z;

                    if (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 > injectorsize * 0.9)
                        maxtorque = maxtorque * 0.9 * injectorsize / (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771);
                }
                torquevector[i] = maxtorque;
                hpvector[i] = maxtorque * 2 * Math.PI * b * 1.34 / 60000;
                boostvector[i] = currentboost;
            }
        }

        public void FillWorkingBuffer()
        {
            for (int i = 0; i < SamplesPerBuffer; i++)
            {
                // Here is where you sample your wave function
                _frequency = rpm / 60;
                _workingBuffer[0, i] = (float)SineWave(_time, _frequency); // channel 1
                _workingBuffer[1, i] = (float)SineWave(_time, _frequency); // 2

                // Advance time passed since beginning
                // Since the amount of samples in a second equals the chosen SampleRate
                // Then each sample should advance the time by 1 / SampleRate
                _time += (2.0 * Math.PI * _frequency) / (SampleRate);
            }
        }

        private void SubmitBuffer()
        {
            FillWorkingBuffer();
            ConvertBuffer(_workingBuffer, _xnaBuffer);
            _instance.SubmitBuffer(_xnaBuffer);
        }


        public void LoadVertices()
        {
            if (g == 1)
                LoadHeightData(heightMap);
            

            VertexMultitextured[] terrainVertices = SetUpTerrainVertices();
            int[] terrainIndices = SetUpTerrainIndices();
            terrainVertices = CalculateNormals(terrainVertices, terrainIndices);

            if (g == 1)
                CopyToTerrainBuffers(terrainVertices, terrainIndices);
            if (g == 2)
                CopyToTerrainBuffers2(terrainVertices, terrainIndices);
            if (g == 3)
                CopyToTerrainBuffers3(terrainVertices, terrainIndices);
            if (g == 4)
                CopyToTerrainBuffers4(terrainVertices, terrainIndices);
            if (g == 5)
                CopyToTerrainBuffers5(terrainVertices, terrainIndices);
            if (g == 6)
                CopyToTerrainBuffers6(terrainVertices, terrainIndices);
            if (g == 7)
                CopyToTerrainBuffers7(terrainVertices, terrainIndices);
            if (g == 8)
                CopyToTerrainBuffers8(terrainVertices, terrainIndices);
            if (g == 9)
                CopyToTerrainBuffers9(terrainVertices, terrainIndices);
            if (g == 10)
                CopyToTerrainBuffers10(terrainVertices, terrainIndices);
            if (g == 11)
                CopyToTerrainBuffers11(terrainVertices, terrainIndices);
            if (g == 12)
                CopyToTerrainBuffers12(terrainVertices, terrainIndices);
            if (g == 13)
                CopyToTerrainBuffers13(terrainVertices, terrainIndices);
            if (g == 14)
                CopyToTerrainBuffers14(terrainVertices, terrainIndices);
            if (g == 15)
                CopyToTerrainBuffers15(terrainVertices, terrainIndices);
            if (g == 16)
                CopyToTerrainBuffers16(terrainVertices, terrainIndices);

            
            terrainVertexDeclaration = new VertexDeclaration(VertexMultitextured.VertexElements);
        }

        private void LoadHeightData(Texture2D heightMap)
        {


            terrainWidth = heightMap.Width;
            terrainLength = heightMap.Height;

            Color[] heightMapColors = new Color[terrainWidth * terrainLength];
            heightMap.GetData(heightMapColors);

            heightData = new float[terrainWidth, terrainLength];
            heightData1 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData2 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData3 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData4 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData5 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData6 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData7 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData8 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData9 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData10 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData11 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData12 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData13 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData14 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData15 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            heightData16 = new float[terrainWidth / 4 + 1, terrainLength / 4 + 1];
            for (int x = 0; x < terrainWidth; x++)
                for (int y = 0; y < terrainLength; y++)
                {
                    heightData[x, y] = heightMapColors[x + y * terrainWidth].R;
                }
            for (int x = 0; x < terrainWidth; x++)
                for (int y = 0; y < terrainLength; y++)
                    heightData[x, y] = heightData[x, y] / 256f * 30f;
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData1[x, y] = heightData[x, y];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData2[x, y] = heightData[x + terrainWidth / 4, y];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData3[x, y] = heightData[x, y + terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData4[x, y] = heightData[x + terrainWidth / 4, y + terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData5[x, y] = heightData[x + 2 * terrainWidth / 4, y];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData6[x, y] = heightData[x, y + 2 *terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData7[x, y] = heightData[x + 2 * terrainWidth / 4, y + terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData8[x, y] = heightData[x + terrainWidth / 4, y + 2 * terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData9[x, y] = heightData[x + 2 * terrainWidth / 4, y + 2 * terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData10[x, y] = heightData[x + 3 * terrainWidth / 4 - 1, y];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData11[x, y] = heightData[x, y + 3 * terrainLength / 4 - 1];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData12[x, y] = heightData[x + 3 * terrainWidth / 4 - 1, y + terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData13[x, y] = heightData[x + terrainWidth / 4, y + 3 * terrainLength / 4 - 1];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData14[x, y] = heightData[x + 3 * terrainWidth / 4 - 1, y + 2 * terrainLength / 4];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData15[x, y] = heightData[x + 2 * terrainWidth / 4, y + 3 * terrainLength / 4 - 1];
                }
            for (int x = 0; x < terrainWidth / 4 + 1; x++)
                for (int y = 0; y < terrainLength / 4 + 1; y++)
                {
                    heightData16[x, y] = heightData[x + 3 * terrainWidth / 4 - 1, y + 3 * terrainLength / 4 - 1];
                }
            if (g == 1)
                heightData = heightData1;
            terrainWidth = terrainWidth / 4 + 1;
            terrainLength = terrainLength / 4 + 1;
        }

        private VertexMultitextured[] SetUpTerrainVertices()
        {
            VertexMultitextured[] terrainVertices = new VertexMultitextured[terrainWidth * terrainLength];

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainLength; y++)
                {
                    terrainVertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y] * (float)relativeheight, -y);
                    terrainVertices[x + y * terrainWidth].TextureCoordinate.X = (float)x / 30.0f;
                    terrainVertices[x + y * terrainWidth].TextureCoordinate.Y = (float)y / 30.0f;

                    terrainVertices[x + y * terrainWidth].TexWeights.X = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 0) / 12.0f, 0, 1);
                    terrainVertices[x + y * terrainWidth].TexWeights.Y = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - (float)textureheight1) / 6.0f, 0, 1);
                    terrainVertices[x + y * terrainWidth].TexWeights.Z = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - (float)textureheight2) / 6.0f, 0, 1);
                    terrainVertices[x + y * terrainWidth].TexWeights.W = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - (float)textureheight3) / 6.0f, 0, 1);

                    float total = terrainVertices[x + y * terrainWidth].TexWeights.X;
                    total += terrainVertices[x + y * terrainWidth].TexWeights.Y;
                    total += terrainVertices[x + y * terrainWidth].TexWeights.Z;
                    total += terrainVertices[x + y * terrainWidth].TexWeights.W;

                    terrainVertices[x + y * terrainWidth].TexWeights.X /= total;
                    terrainVertices[x + y * terrainWidth].TexWeights.Y /= total;
                    terrainVertices[x + y * terrainWidth].TexWeights.Z /= total;
                    terrainVertices[x + y * terrainWidth].TexWeights.W /= total;
                }
            }

            return terrainVertices;
        }

        private int[] SetUpTerrainIndices()
        {
            int[] indices = new int[(terrainWidth - 1) * (terrainLength - 1) * 6];
            int counter = 0;
            for (int y = 0; y < terrainLength - 1; y++)
            {
                for (int x = 0; x < terrainWidth - 1; x++)
                {
                    int lowerLeft = x + y * terrainWidth;
                    int lowerRight = (x + 1) + y * terrainWidth;
                    int topLeft = x + (y + 1) * terrainWidth;
                    int topRight = (x + 1) + (y + 1) * terrainWidth;

                    indices[counter++] = topLeft;
                    indices[counter++] = lowerRight;
                    indices[counter++] = lowerLeft;

                    indices[counter++] = topLeft;
                    indices[counter++] = topRight;
                    indices[counter++] = lowerRight;
                }
            }

            return indices;
        }

        private VertexMultitextured[] CalculateNormals(VertexMultitextured[] vertices, int[] indices)
        {
            for (int i = 0; i < vertices.Length; i++)
                vertices[i].Normal = new Vector3(0, 0, 0);

            for (int i = 0; i < indices.Length / 3; i++)
            {
                int index1 = indices[i * 3];
                int index2 = indices[i * 3 + 1];
                int index3 = indices[i * 3 + 2];

                Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
                Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
                Vector3 normal = Vector3.Cross(side1, side2);

                vertices[index1].Normal += normal;
                vertices[index2].Normal += normal;
                vertices[index3].Normal += normal;
            }

            for (int i = 0; i < vertices.Length; i++)
                vertices[i].Normal.Normalize();

            return vertices;
        }

        public void CopyToTerrainBuffers(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer.SetData(indices);
        }

        public void CopyToTerrainBuffers2(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer2 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly);
            terrainVertexBuffer2.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer2 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer2.SetData(indices);
        }

        public void CopyToTerrainBuffers3(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer3 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly);
            terrainVertexBuffer3.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer3 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer3.SetData(indices);
        }

        public void CopyToTerrainBuffers4(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer4 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly);
            terrainVertexBuffer4.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer4 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer4.SetData(indices);
        }

        public void CopyToTerrainBuffers5(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer5 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer5.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer5 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer5.SetData(indices);
        }

        public void CopyToTerrainBuffers6(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer6 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer6.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer6 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer6.SetData(indices);
        }

        public void CopyToTerrainBuffers7(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer7 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer7.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer7 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer7.SetData(indices);
        }

        public void CopyToTerrainBuffers8(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer8 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer8.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer8 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer8.SetData(indices);
        }

        public void CopyToTerrainBuffers9(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer9 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer9.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer9 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer9.SetData(indices);
        }

        public void CopyToTerrainBuffers10(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer10 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer10.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer10 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer10.SetData(indices);
        }

        public void CopyToTerrainBuffers11(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer11 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer11.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer11 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer11.SetData(indices);
        }

        public void CopyToTerrainBuffers12(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer12 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer12.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer12 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer12.SetData(indices);
        }

        public void CopyToTerrainBuffers13(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer13 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer13.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer13 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer13.SetData(indices);
        }

        public void CopyToTerrainBuffers14(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer14 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer14.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer14 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer14.SetData(indices);
        }

        public void CopyToTerrainBuffers15(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer15 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer15.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer15 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer15.SetData(indices);
        }

        public void CopyToTerrainBuffers16(VertexMultitextured[] vertices, int[] indices)
        {
            terrainVertexBuffer16 = new VertexBuffer(device, new VertexDeclaration(VertexMultitextured.VertexElements), vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.None);
            terrainVertexBuffer16.SetData(vertices);
            f = indices.Length;
            terrainIndexBuffer16 = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            terrainIndexBuffer16.SetData(indices);
        }

        double Distance(Vector3 worldposition, Vector3 positionvector)
        {
            worlddistance = Math.Pow(Math.Pow((float)worldposition.X - (double)positionvector.X + terrainLength / 2, 2) + Math.Pow((double)worldposition.Y - (double)positionvector.Y + terrainLength / 2, 2) + Math.Pow((float)worldposition.Z - (float)positionvector.Z, 2), 0.5);
            return worlddistance;
        }

        public static double Distance2(Vector3 v1, Vector3 v2)
        {
            return
            (
               Math.Sqrt
               (
                   (v1.X - v2.X) * (v1.X - v2.X) +
                   (v1.Y - v2.Y) * (v1.Y - v2.Y) +
                   (v1.Z - v2.Z) * (v1.Z - v2.Z)
               )
            );
        }


        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState = Keyboard.GetState();
            MouseState = Mouse.GetState();

            counter = 0;
            acceleration = 0;

            if (KeyboardState.IsKeyDown(Keys.Escape))
                menu = 6;

            collisionfzrf = 0;
            collisionfzrb = 0;
            collisionfzlf = 0;
            collisionfzlb = 0;

            if (finish)
                opponent = 0;

            if (opponent != 0)
                driveopponent();

            torque = 0;
            if (stationary)
                direction = 1;


            if (positionx > -5 & positionx < 1 & positiony > 17 & positiony < 23 & stationary)
            {
                menu = 2.1;
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 20)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 20)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5)
                {
                    if (arrowy == 200)
                    {
                        positionx = 3;
                        menu = 1;
                    }
                    if (arrowy == 400)
                    {
                        currentmap = Content.Load<map>("maps/rockypass/rocky_pass");
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 440)
                    {
                        currentmap = Content.Load<map>("maps/riverbasin/river_basin");
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 480)
                    {
                        currentmap = Content.Load<map>("maps/hillsbrad/hillsbrad_1");
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 520)
                    {
                        currentmap = Content.Load<map>("maps/cliffs/deathroad");
                        newmap();
                        menu = 1;
                    }
                }
            }



            if (positionx > -55 & positionx < -49 & positiony > 17 & positiony < 23 & stationary)
            {
                menu = 2.2;
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 20)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 20)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Left) & pause > 5)
                {
                    arrowx = arrowx - 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Right) & pause > 5)
                {
                    arrowx = arrowx + 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 200)
                {
                    if (arrowy == 200)
                    {
                        menu = 1;
                        positionx = -40;
                    }
                    if (arrowy == 220)
                    {
                        currentmap = Content.Load<map>("maps/freeroam/drag402");
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        currentmap = Content.Load<map>("maps/freeroam/drag1000");
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 400 & currentmap.checkpointx[0] == -56)
                {
                    if (arrowy == 200)
                    {
                        menu = 1;
                    }
                    if (arrowy == 220)
                    {
                        currentopponent = Content.Load<opponent>("opponents/2500ccNA");                       
                        for (int u = 0; u < 2; u++)
                        {
                            randomvector[u] = random.NextDouble();
                        }
                        if (randomvector[1] < 1 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot1);
                        else if (randomvector[1] < 2 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot2);
                        else if (randomvector[1] < 3 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot3);
                        else if (randomvector[1] < 4 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot4);
                        else if (randomvector[1] < 5 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot5);
                        else if (randomvector[1] < 6 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot6);
                        else if (randomvector[1] < 7 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot7);
                        else if (randomvector[1] < 8 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot8);
                        else if (randomvector[1] < 9 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot9);
                        else if (randomvector[1] < 10 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot10);
                        else if (randomvector[1] < 11 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot11);
                        else if (randomvector[1] < 12 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot12);
                        else if (randomvector[1] < 13 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot13);
                        else if (randomvector[1] < 14 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot14);
                        else if (randomvector[1] < 15 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot15);
                        else if (randomvector[1] < 16 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot16);
                        else if (randomvector[1] < 17 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot17);
                        else if (randomvector[1] < 18 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot18);
                        else if (randomvector[1] < 19 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot19);
                        else if (randomvector[1] < 20 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot20);
                        else if (randomvector[1] < 21 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot21);
                        else if (randomvector[1] < 22 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot22);
                        else if (randomvector[1] < 23 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot23);
                        else if (randomvector[1] < 24 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot24);
                        else if (randomvector[1] < 25 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot25);
                        else if (randomvector[1] < 26 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot26);
                        else if (randomvector[1] < 27 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot27);
                        else if (randomvector[1] < 28 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot28);
                        //else if (randomvector[1] < 29 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot29);
                        //else if (randomvector[1] < 30 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot30);
                        //else if (randomvector[1] < 31 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot31);
                        //else
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot32);
                        newopponent();
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        currentopponent = Content.Load<opponent>("opponents/fwdtuner");
                        for (int u = 0; u < 2; u++)
                        {
                            randomvector[u] = random.NextDouble();
                        }
                        if (randomvector[1] < 1 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot1);
                        else if (randomvector[1] < 2 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot2);
                        else if (randomvector[1] < 3 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot3);
                        else if (randomvector[1] < 4 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot4);
                        else if (randomvector[1] < 5 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot5);
                        else if (randomvector[1] < 6 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot6);
                        else if (randomvector[1] < 7 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot7);
                        else if (randomvector[1] < 8 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot8);
                        else if (randomvector[1] < 9 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot9);
                        else if (randomvector[1] < 10 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot10);
                        else if (randomvector[1] < 11 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot11);
                        else if (randomvector[1] < 12 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot12);
                        else if (randomvector[1] < 13 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot13);
                        else if (randomvector[1] < 14 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot14);
                        else if (randomvector[1] < 15 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot15);
                        else if (randomvector[1] < 16 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot16);
                        else if (randomvector[1] < 17 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot17);
                        else if (randomvector[1] < 18 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot18);
                        else if (randomvector[1] < 19 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot19);
                        else if (randomvector[1] < 20 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot20);
                        else if (randomvector[1] < 21 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot21);
                        else if (randomvector[1] < 22 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot22);
                        else if (randomvector[1] < 23 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot23);
                        else if (randomvector[1] < 24 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot24);
                        else if (randomvector[1] < 25 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot25);
                        else if (randomvector[1] < 26 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot26);
                        else if (randomvector[1] < 27 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot27);
                        //else if (randomvector[1] < 28 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot28);
                        //else if (randomvector[1] < 29 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot29);
                        //else if (randomvector[1] < 30 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot30);
                        //else if (randomvector[1] < 31 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot31);
                        //else
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot32);
                        newopponent();
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 260)
                    {
                        currentopponent = Content.Load<opponent>("opponents/test");
                        for (int u = 0; u < 2; u++)
                        {
                            randomvector[u] = random.NextDouble();
                        }
                        if (randomvector[1] < 1 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot1);
                        else if (randomvector[1] < 2 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot2);
                        else if (randomvector[1] < 3 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot3);
                        else if (randomvector[1] < 4 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot4);
                        else if (randomvector[1] < 5 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot5);
                        else if (randomvector[1] < 6 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot6);
                        else if (randomvector[1] < 7 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot7);
                        else if (randomvector[1] < 8 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot8);
                        else if (randomvector[1] < 9 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot9);
                        else if (randomvector[1] < 10 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot10);
                        else if (randomvector[1] < 11 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot11);
                        else if (randomvector[1] < 12 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot12);
                        else if (randomvector[1] < 13 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot13);
                        else if (randomvector[1] < 14 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot14);
                        else if (randomvector[1] < 15 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot15);
                        else if (randomvector[1] < 16 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot16);
                        else if (randomvector[1] < 17 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot17);
                        else if (randomvector[1] < 18 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot18);
                        else if (randomvector[1] < 19 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot19);
                        else if (randomvector[1] < 20 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot20);
                        else if (randomvector[1] < 21 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot21);
                        else if (randomvector[1] < 22 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot22);
                        else if (randomvector[1] < 23 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot23);
                        else if (randomvector[1] < 24 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot24);
                        else if (randomvector[1] < 25 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot25);
                        else if (randomvector[1] < 26 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot26);
                        else if (randomvector[1] < 27 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot27);
                        else if (randomvector[1] < 28 / 32f)
                            currentvehicle = Content.Load<vehicle>(currentopponent.lot28);
                        //else if (randomvector[1] < 29 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot29);
                        //else if (randomvector[1] < 30 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot30);
                        //else if (randomvector[1] < 31 / 32f)
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot31);
                        //else
                        //    currentvehicle = Content.Load<vehicle>(currentopponent.lot32);
                        newopponent();
                        newmap();
                        menu = 1;
                    }
                    if (arrowy == 280)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot4);
                        newmap();
                        newopponent();
                        menu = 1;
                    }
                }
            }

            if (menu == 1 & pause3 > 60)
                carshopcheck();
            
            if (menu == 3 & currentcarshop.type == "junkyard")
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 5)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 5)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Left) & pause > 5)
                {
                    arrowx = arrowx - 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Right) & pause > 5)
                {
                    arrowx = arrowx + 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 200)
                {
                    if (arrowy == 200)
                    {
                        positionx = positionx - 6;
                        menu = 1;
                    }
                    if (arrowy == 220 & randomvector[0] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot1);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 240 & randomvector[1] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot2);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 260 & randomvector[2] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot3);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 280 & randomvector[3] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot4);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 300 & randomvector[4] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot5);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 320 & randomvector[5] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot6);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 340 & randomvector[6] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot7);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 360 & randomvector[7] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot8);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 380 & randomvector[8] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot9);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 400 & randomvector[9] < 0.3)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot10);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 420 & randomvector[10] < 0.2)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot11);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 440 & randomvector[11] < 0.2)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot12);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 460 & randomvector[12] < 0.2)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot13);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 480 & randomvector[13] < 0.2)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot14);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 500 & randomvector[14] < 0.2)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot15);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 520 & randomvector[15] < 0.1)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot16);
                        newvehicle();
                        menu = 1;
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 400)
                {
                    if (arrowy == 220 & randomvector[16] < 0.1)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot17);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 240 & randomvector[17] < 0.1)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot18);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 260 & randomvector[18] < 0.1)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot19);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 280 & randomvector[19] < 0.1)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot20);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 300 & randomvector[20] < 0.05)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot21);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 320 & randomvector[21] < 0.05)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot22);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 340 & randomvector[22] < 0.05)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot23);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 360 & randomvector[23] < 0.05)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot25);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 380 & randomvector[24] < 0.05)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot25);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 400 & randomvector[25] < 0.03)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot26);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 420 & randomvector[26] < 0.03)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot27);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 440 & randomvector[27] < 0.03)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot28);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 460 & randomvector[28] < 0.03)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot29);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 480 & randomvector[29] < 0.03)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot30);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 500 & randomvector[30] < 0.01)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot31);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 520 & randomvector[31] < 0.01)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot32);
                        newvehicle();
                        menu = 1;
                    }
                }
            }

            if (menu == 3 & currentcarshop.type == "dealer")
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 5)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 5)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Left) & pause > 5)
                {
                    arrowx = arrowx - 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Right) & pause > 5)
                {
                    arrowx = arrowx + 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 200)
                {
                    if (arrowy == 200)
                    {
                        positionx = positionx - 6;
                        menu = 1;
                    }
                    if (arrowy == 220)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot1);
                        newvehicle();
                        positionx = -56;
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot2);
                        newvehicle();
                        positionx = -56;
                        menu = 1;
                    }
                    if (arrowy == 260)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot3);
                        newvehicle();
                        positionx = -56;
                        menu = 1;
                    }
                    if (arrowy == 280)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot4);
                        newvehicle();
                        positionx = -56;
                        menu = 1;
                    }
                    if (arrowy == 300)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot5);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 320)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot6);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 340)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot7);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 360)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot8);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 380)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot9);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 400)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot10);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 420)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot11);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 440)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot12);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 460)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot13);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 480)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot14);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 500)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot15);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 520)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot16);
                        newvehicle();
                        menu = 1;
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 400)
                {
                    if (arrowy == 220)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot17);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot18);
                        newvehicle();
                        positionx = -56;
                        menu = 1;
                    }
                    if (arrowy == 260)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot19);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 280)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot20);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 300)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot21);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 320)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot22);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 340)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot23);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 360)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot24);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 380)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot25);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 400)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot26);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 420)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot27);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 440)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot28);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 460)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot29);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 480)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot30);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 500)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot31);
                        newvehicle();
                        menu = 1;
                    }
                    if (arrowy == 520)
                    {
                        currentvehicle = Content.Load<vehicle>(currentcarshop.lot32);
                        newvehicle();
                        menu = 1;
                    }
                }
            }


            if (menu == 1 & pause3 > 59)
                partshopcheck();

            if (menu == 5)
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 20)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 20)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5)
                {
                    if (arrowy == 200)
                    {
                        positionx = 3;
                        menu = 1;
                    }
                    if (arrowy == 220)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott1);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott2);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 260)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott3);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 280)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott4);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 300)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott5);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 320)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott6);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 340)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott7);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 360)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott8);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 380)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott9);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 400)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott10);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 420)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott11);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 440)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott12);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 460)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott13);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 480)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott14);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 500)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott15);
                        newpart();
                        menu = 1;
                    }
                    if (arrowy == 520)
                    {
                        currentpart = Content.Load<part>(currentpartshop.lott16);
                        newpart();
                        menu = 1;
                    }
                }
            }


            if (positionx > -25 & positionx < -19 & positiony > 17 & positiony < 23 & stationary)
            {
                if (menu == 1)
                    menu = 4;            
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 20)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 20)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & menu == 4)
                {
                    if (arrowy == 200)
                    {
                        positionx = -20;
                        positiony = -5;
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        dyno();
                        menu = 10;
                    }
                    if (arrowy == 260 & customecu)
                    {
                        menu = 4.1;
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & menu == 10)
                {
                    if (arrowy == 200)
                    {
                        menu = 4;
                    }
                }
            }

            if (menu == 4.1)
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 10)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 10)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Left) & pause > 10)
                {
                    arrowx = arrowx - 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Right) & pause > 10)
                {
                    arrowx = arrowx + 100;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 200 & customecu)
                {
                    if (arrowy == 200)
                    {
                        positionx = -20;
                        positiony = -5;
                        menu = 1;
                    }
                    if (arrowy == 220)
                    {
                        rpm250.Y = (float)(rpm250.Y + 0.02);
                    }
                    if (arrowy == 240)
                    {
                        rpm500.Y = (float)(rpm2500.Y + 0.02);
                    }
                    if (arrowy == 260)
                    {
                        rpm750.Y = (float)(rpm750.Y + 0.02);
                    }
                    if (arrowy == 280)
                    {
                        rpm1000.Y = (float)(rpm1000.Y + 0.02);
                    }
                    if (arrowy == 300)
                    {
                        rpm1250.Y = (float)(rpm1250.Y + 0.02);
                    }
                    if (arrowy == 320)
                    {
                        rpm1500.Y = (float)(rpm1500.Y + 0.02);
                    }
                    if (arrowy == 340)
                    {
                        rpm1750.Y = (float)(rpm1750.Y + 0.02);
                    }
                    if (arrowy == 360)
                    {
                        rpm2000.Y = (float)(rpm2000.Y + 0.02);
                    }
                    if (arrowy == 380)
                    {
                        rpm2250.Y = (float)(rpm2250.Y + 0.02);
                    }
                    if (arrowy == 400)
                    {
                        rpm2500.Y = (float)(rpm2500.Y + 0.02);
                    }
                    if (arrowy == 420)
                    {
                        rpm2750.Y = (float)(rpm2750.Y + 0.02);
                    }
                    if (arrowy == 440)
                    {
                        rpm3000.Y = (float)(rpm3000.Y + 0.02);
                    }
                    if (arrowy == 460)
                    {
                        rpm3250.Y = (float)(rpm3250.Y + 0.02);
                    }
                    if (arrowy == 480)
                    {
                        rpm3500.Y = (float)(rpm3500.Y + 0.02);
                    }
                    if (arrowy == 500)
                    {
                        rpm3750.Y = (float)(rpm3750.Y + 0.02);
                    }
                    if (arrowy == 520)
                    {
                        rpm4000.Y = (float)(rpm4000.Y + 0.02);
                    }
                    if (arrowy == 540)
                    {
                        rpm4250.Y = (float)(rpm4250.Y + 0.02);
                    }
                    if (arrowy == 560)
                    {
                        rpm4500.Y = (float)(rpm4500.Y + 0.02);
                    }
                    if (arrowy == 580)
                    {
                        rpm4750.Y = (float)(rpm4750.Y + 0.02);
                    }
                    if (arrowy == 600)
                    {
                        rpm5000.Y = (float)(rpm5000.Y + 0.02);
                    }
                    if (arrowy == 620)
                    {
                        rpm5250.Y = (float)(rpm5250.Y + 0.02);
                    }
                    if (arrowy == 640)
                    {
                        rpm5500.Y = (float)(rpm5500.Y + 0.02);
                    }
                    if (arrowy == 660)
                    {
                        rpm5750.Y = (float)(rpm5750.Y + 0.02);
                    }
                    if (arrowy == 680)
                    {
                        rpm6000.Y = (float)(rpm6000.Y + 0.02);
                    }
                    if (arrowy == 700)
                    {
                        rpm6250.Y = (float)(rpm6250.Y + 0.02);
                    }
                    if (arrowy == 720)
                    {
                        rpm6500.Y = (float)(rpm6500.Y + 0.02);
                    }
                    if (arrowy == 740)
                    {
                        rpm6750.Y = (float)(rpm6750.Y + 0.02);
                    }
                    if (arrowy == 760)
                    {
                        rpm7000.Y = (float)(rpm7000.Y + 0.02);
                    }
                    if (arrowy == 780)
                    {
                        rpm7250.Y = (float)(rpm7250.Y + 0.02);
                    }
                    if (arrowy == 800)
                    {
                        rpm7500.Y = (float)(rpm7500.Y + 0.02);
                    }
                    if (arrowy == 820)
                    {
                        rpm7750.Y = (float)(rpm7750.Y + 0.02);
                    }
                    if (arrowy == 840)
                    {
                        rpm8000.Y = (float)(rpm8000.Y + 0.02);
                    }
                    if (arrowy == 860)
                    {
                        rpm8250.Y = (float)(rpm8250.Y + 0.02);
                    }
                    if (arrowy == 880)
                    {
                        rpm8500.Y = (float)(rpm8500.Y + 0.02);
                    }
                    if (arrowy == 900)
                    {
                        rpm8750.Y = (float)(rpm8750.Y + 0.02);
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 300 & customecu)
                {
                    if (arrowy == 200)
                    {
                        positionx = -20;
                        positiony = -5;
                        menu = 1;
                    }
                    if (arrowy == 220)
                    {
                        rpm250.Y = (float)(rpm250.Y - 0.02);
                    }
                    if (arrowy == 240)
                    {
                        rpm500.Y = (float)(rpm2500.Y - 0.02);
                    }
                    if (arrowy == 260)
                    {
                        rpm750.Y = (float)(rpm750.Y - 0.02);
                    }
                    if (arrowy == 280)
                    {
                        rpm1000.Y = (float)(rpm1000.Y - 0.02);
                    }
                    if (arrowy == 300)
                    {
                        rpm1250.Y = (float)(rpm1250.Y - 0.02);
                    }
                    if (arrowy == 320)
                    {
                        rpm1500.Y = (float)(rpm1500.Y - 0.02);
                    }
                    if (arrowy == 340)
                    {
                        rpm1750.Y = (float)(rpm1750.Y - 0.02);
                    }
                    if (arrowy == 360)
                    {
                        rpm2000.Y = (float)(rpm2000.Y - 0.02);
                    }
                    if (arrowy == 380)
                    {
                        rpm2250.Y = (float)(rpm2250.Y - 0.02);
                    }
                    if (arrowy == 400)
                    {
                        rpm2500.Y = (float)(rpm2500.Y - 0.02);
                    }
                    if (arrowy == 420)
                    {
                        rpm2750.Y = (float)(rpm2750.Y - 0.02);
                    }
                    if (arrowy == 440)
                    {
                        rpm3000.Y = (float)(rpm3000.Y - 0.02);
                    }
                    if (arrowy == 460)
                    {
                        rpm3250.Y = (float)(rpm3250.Y - 0.02);
                    }
                    if (arrowy == 480)
                    {
                        rpm3500.Y = (float)(rpm3500.Y - 0.02);
                    }
                    if (arrowy == 500)
                    {
                        rpm3750.Y = (float)(rpm3750.Y - 0.02);
                    }
                    if (arrowy == 520)
                    {
                        rpm4000.Y = (float)(rpm4000.Y - 0.02);
                    }
                    if (arrowy == 540)
                    {
                        rpm4250.Y = (float)(rpm4250.Y - 0.02);
                    }
                    if (arrowy == 560)
                    {
                        rpm4500.Y = (float)(rpm4500.Y - 0.02);
                    }
                    if (arrowy == 580)
                    {
                        rpm4750.Y = (float)(rpm4750.Y - 0.02);
                    }
                    if (arrowy == 600)
                    {
                        rpm5000.Y = (float)(rpm5000.Y - 0.02);
                    }
                    if (arrowy == 620)
                    {
                        rpm5250.Y = (float)(rpm5250.Y - 0.02);
                    }
                    if (arrowy == 640)
                    {
                        rpm5500.Y = (float)(rpm5500.Y - 0.02);
                    }
                    if (arrowy == 660)
                    {
                        rpm5750.Y = (float)(rpm5750.Y - 0.02);
                    }
                    if (arrowy == 680)
                    {
                        rpm6000.Y = (float)(rpm6000.Y - 0.02);
                    }
                    if (arrowy == 700)
                    {
                        rpm6250.Y = (float)(rpm6250.Y - 0.02);
                    }
                    if (arrowy == 720)
                    {
                        rpm6500.Y = (float)(rpm6500.Y - 0.02);
                    }
                    if (arrowy == 740)
                    {
                        rpm6750.Y = (float)(rpm6750.Y - 0.02);
                    }
                    if (arrowy == 760)
                    {
                        rpm7000.Y = (float)(rpm7000.Y - 0.02);
                    }
                    if (arrowy == 780)
                    {
                        rpm7250.Y = (float)(rpm7250.Y - 0.02);
                    }
                    if (arrowy == 800)
                    {
                        rpm7500.Y = (float)(rpm7500.Y - 0.02);
                    }
                    if (arrowy == 820)
                    {
                        rpm7750.Y = (float)(rpm7750.Y - 0.02);
                    }
                    if (arrowy == 840)
                    {
                        rpm8000.Y = (float)(rpm8000.Y - 0.02);
                    }
                    if (arrowy == 860)
                    {
                        rpm8250.Y = (float)(rpm8250.Y - 0.02);
                    }
                    if (arrowy == 880)
                    {
                        rpm8500.Y = (float)(rpm8500.Y - 0.02);
                    }
                    if (arrowy == 900)
                    {
                        rpm8750.Y = (float)(rpm8750.Y - 0.02);
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 400 & customecu)
                {
                    if (arrowy == 220)
                    {
                        maxrpm = maxrpm + 10;
                    }
                    if (arrowy == 240)
                    {
                        maxrpm = maxrpm - 10;
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5 & arrowx == 400 & customecu)
                {
                    if (arrowy == 280)
                    {
                        launchrpm = launchrpm + 10;
                    }
                    if (arrowy == 300)
                    {
                        launchrpm = launchrpm - 10;
                    }
                }
            }

            if (menu == 6)
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > 20)
                {
                    arrowy = arrowy - 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) & pause > 20)
                {
                    arrowy = arrowy + 20;
                    pause = 0;
                }
                if (KeyboardState.IsKeyDown(Keys.Enter) & pause > 5)
                {
                    if (arrowy == 200)
                    {
                        menu = 1;
                    }
                    if (arrowy == 240)
                    {
                        controls = 1;
                        this.IsMouseVisible = false;
                    }
                    if (arrowy == 260)
                    {
                        controls = 2;
                        this.IsMouseVisible = true;
                    }
                }
            }




            if (finish == false & positionx > checkpointx[checkpoint] - 1.5 & positionx < checkpointx[checkpoint] + 1.5 & positiony > checkpointy[checkpoint] - 1.5 & positiony < checkpointy[checkpoint] + 1.5)
            {
                checkpoint = checkpoint + 1;
                if (checkpoint == checkpointx.Length - 1)
                {
                    finish = true;
                    trap5 = time / 60;
                    opponent = 0;
                }
            }

            if (opponent != 0 & finish == false & positiony2 > checkpointy[checkpoint] - 1.5)
            {
                finish = true;
                trap5 = time / 60;
                opponent = 0;
            }



            wheelposrfx = positionx + wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) + wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposrfy = positiony - wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) + wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposrbx = positionx + wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) - wheelbaselength / 2 * dx * Math.Cos(slopeangle);                // calculate position of each wheel
            wheelposrby = positiony - wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) - wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposlfx = positionx - wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) + wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposlfy = positiony + wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) + wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposlbx = positionx - wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) - wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposlby = positiony + wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) - wheelbaselength / 2 * dy * Math.Cos(slopeangle);


            wheelposrfx /= relativescale;
            wheelposrbx /= relativescale;
            wheelposlfx /= relativescale;
            wheelposlbx /= relativescale;

            wheelposrfy /= relativescale;
            wheelposrby /= relativescale;
            wheelposlfy /= relativescale;
            wheelposlby /= relativescale;

            positionx /= relativescale;
            positiony /= relativescale;

            if (positionx > 0 + wheelbaselength & positionx < heightMap.Width - wheelbaselength & positiony > 0 + wheelbaselength & positiony < heightMap.Height - wheelbaselength)
            {
                if (surface == 1)
                    tyrebasegrip = Tyretype.X;
                if (surface == 2)
                    tyrebasegrip = Tyretype.Y;
                if (surface == 3)
                    tyrebasegrip = Tyretype.Z;
                if (surface == 4)
                    tyrebasegrip = Tyretype.W;


                
                a = wheelposrfx - Math.Floor(wheelposrfx);
                b = wheelposrfy - Math.Floor(wheelposrfy);

                c = (heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))] + (wheelposrfx - Math.Floor(wheelposrfx)) / (Math.Ceiling(wheelposrfx) - Math.Floor(wheelposrfx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))])) * (1 - b) + (heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Ceiling(wheelposrfy))] + (wheelposrfx - Math.Floor(wheelposrfx)) / (Math.Ceiling(wheelposrfx) - Math.Floor(wheelposrfx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrfx)), Convert.ToInt32(Math.Ceiling(wheelposrfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Ceiling(wheelposrfy))])) * b;
                d = (heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))] + (wheelposrfy - Math.Floor(wheelposrfy)) / (Math.Ceiling(wheelposrfy) - Math.Floor(wheelposrfy)) * (heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Ceiling(wheelposrfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))])) * (1 - a) + (heightData[Convert.ToInt32(Math.Ceiling(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))] + (wheelposrfy - Math.Floor(wheelposrfy)) / (Math.Ceiling(wheelposrfy) - Math.Floor(wheelposrfy)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrfx)), Convert.ToInt32(Math.Ceiling(wheelposrfy))] - heightData[Convert.ToInt32(Math.Ceiling(wheelposrfx)), Convert.ToInt32(Math.Floor(wheelposrfy))])) * a;
                floorrf = (c + d) / 2 * relativeheight * relativescale;

                a = wheelposrbx - Math.Floor(wheelposrbx);
                b = wheelposrby - Math.Floor(wheelposrby);

                c = (heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))] + (wheelposrbx - Math.Floor(wheelposrbx)) / (Math.Ceiling(wheelposrbx) - Math.Floor(wheelposrbx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))] - heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))])) * (1 - b) + (heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Ceiling(wheelposrby))] + (wheelposrbx - Math.Floor(wheelposrbx)) / (Math.Ceiling(wheelposrbx) - Math.Floor(wheelposrbx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrbx)), Convert.ToInt32(Math.Ceiling(wheelposrby))] - heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Ceiling(wheelposrby))])) * b;
                d = (heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))] + (wheelposrby - Math.Floor(wheelposrby)) / (Math.Ceiling(wheelposrby) - Math.Floor(wheelposrby)) * (heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Ceiling(wheelposrby))] - heightData[Convert.ToInt32(Math.Floor(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))])) * (1 - a) + (heightData[Convert.ToInt32(Math.Ceiling(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))] + (wheelposrby - Math.Floor(wheelposrby)) / (Math.Ceiling(wheelposrby) - Math.Floor(wheelposrby)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposrbx)), Convert.ToInt32(Math.Ceiling(wheelposrby))] - heightData[Convert.ToInt32(Math.Ceiling(wheelposrbx)), Convert.ToInt32(Math.Floor(wheelposrby))])) * a;
                floorrb = (c + d) / 2 * relativeheight * relativescale;

                a = wheelposlfx - Math.Floor(wheelposlfx);                         // extrapollate height of terrain at each wheel
                b = wheelposlfy - Math.Floor(wheelposlfy);

                c = (heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))] + (wheelposlfx - Math.Floor(wheelposlfx)) / (Math.Ceiling(wheelposlfx) - Math.Floor(wheelposlfx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))])) * (1 - b) + (heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Ceiling(wheelposlfy))] + (wheelposlfx - Math.Floor(wheelposlfx)) / (Math.Ceiling(wheelposlfx) - Math.Floor(wheelposlfx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlfx)), Convert.ToInt32(Math.Ceiling(wheelposlfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Ceiling(wheelposlfy))])) * b;
                d = (heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))] + (wheelposlfy - Math.Floor(wheelposlfy)) / (Math.Ceiling(wheelposlfy) - Math.Floor(wheelposlfy)) * (heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Ceiling(wheelposlfy))] - heightData[Convert.ToInt32(Math.Floor(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))])) * (1 - a) + (heightData[Convert.ToInt32(Math.Ceiling(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))] + (wheelposlfy - Math.Floor(wheelposlfy)) / (Math.Ceiling(wheelposlfy) - Math.Floor(wheelposlfy)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlfx)), Convert.ToInt32(Math.Ceiling(wheelposlfy))] - heightData[Convert.ToInt32(Math.Ceiling(wheelposlfx)), Convert.ToInt32(Math.Floor(wheelposlfy))])) * a;
                floorlf = (c + d) / 2 * relativeheight * relativescale;

                a = wheelposlbx - Math.Floor(wheelposlbx);
                b = wheelposlby - Math.Floor(wheelposlby);

                c = (heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))] + (wheelposlbx - Math.Floor(wheelposlbx)) / (Math.Ceiling(wheelposlbx) - Math.Floor(wheelposlbx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))] - heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))])) * (1 - b) + (heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Ceiling(wheelposlby))] + (wheelposlbx - Math.Floor(wheelposlbx)) / (Math.Ceiling(wheelposlbx) - Math.Floor(wheelposlbx)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlbx)), Convert.ToInt32(Math.Ceiling(wheelposlby))] - heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Ceiling(wheelposlby))])) * b;
                d = (heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))] + (wheelposlby - Math.Floor(wheelposlby)) / (Math.Ceiling(wheelposlby) - Math.Floor(wheelposlby)) * (heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Ceiling(wheelposlby))] - heightData[Convert.ToInt32(Math.Floor(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))])) * (1 - a) + (heightData[Convert.ToInt32(Math.Ceiling(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))] + (wheelposlby - Math.Floor(wheelposlby)) / (Math.Ceiling(wheelposlby) - Math.Floor(wheelposlby)) * (heightData[Convert.ToInt32(Math.Ceiling(wheelposlbx)), Convert.ToInt32(Math.Ceiling(wheelposlby))] - heightData[Convert.ToInt32(Math.Ceiling(wheelposlbx)), Convert.ToInt32(Math.Floor(wheelposlby))])) * a;
                floorlb = (c + d) / 2 * relativeheight * relativescale;
            }
            else
            {
                tyrebasegrip = Tyretype.X;
                floorrf = 0;
                floorlf = 0;
                floorrb = 0;
                floorlb = 0;
            }

            wheelposrfx *= relativescale;
            wheelposrbx *= relativescale;
            wheelposlfx *= relativescale;
            wheelposlbx *= relativescale;

            wheelposrfy *= relativescale;
            wheelposrby *= relativescale;
            wheelposlfy *= relativescale;
            wheelposlby *= relativescale;

            positionx *= relativescale;
            positiony *= relativescale;



            foreach (ModelMesh mesh in collisionmodel.Meshes)
            {
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                {
                    // Vertex buffer parameters
                    int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride;
                    int vertexBufferSize = meshPart.NumVertices * vertexStride;

                    // Get vertex data as float
                    float[] vertexData = new float[vertexBufferSize / sizeof(float)];
                    meshPart.VertexBuffer.GetData<float>(vertexData);

                    // Iterate through vertices (possibly) growing bounding box, all calculations are done in world space
                    for (int i = 0; i < vertexBufferSize / sizeof(float); i += vertexStride / sizeof(float))
                    {
                        Vector3 transformedPosition = Vector3.Transform(new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]), world0);
                        meshvector = new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]);
                        counter = counter + 1;
                        vertexData[i] = transformedPosition.X;
                        vertexData[i + 1] = transformedPosition.Y;
                        vertexData[i + 2] = transformedPosition.Z;
                        a = vertexData[i];
                        b = vertexData[i + 1];
                        c = vertexData[i + 2];
                        if (positiony > 8)
                            c = a;
                        
                        if (positionx > 0 + wheelbaselength * 1.2 & positionx < heightMap.Width - wheelbaselength * 1.2 & positiony > 0 + wheelbaselength * 1.2 & positiony * 1.2 < heightMap.Height - wheelbaselength * 1.2)
                        {
                            a = vertexData[i] - Math.Floor(vertexData[i]);
                            b = vertexData[i + 1] - Math.Floor(vertexData[i + 1]);

                            c = (heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))] + (vertexData[i] - Math.Floor(vertexData[i])) / (Math.Ceiling(vertexData[i]) - Math.Floor(vertexData[i])) * (heightData[Convert.ToInt32(Math.Ceiling(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))] - heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))])) * (1 - b) + (heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Ceiling(vertexData[i + 1]))] + (vertexData[i] - Math.Floor(vertexData[i])) / (Math.Ceiling(vertexData[i]) - Math.Floor(vertexData[i])) * (heightData[Convert.ToInt32(Math.Ceiling(vertexData[i])), Convert.ToInt32(Math.Ceiling(vertexData[i + 1]))] - heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Ceiling(vertexData[i + 1]))])) * b;
                            d = (heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))] + (vertexData[i + 1] - Math.Floor(vertexData[i + 1])) / (Math.Ceiling(vertexData[i + 1]) - Math.Floor(vertexData[i + 1])) * (heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Ceiling(vertexData[i + 1]))] - heightData[Convert.ToInt32(Math.Floor(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))])) * (1 - a) + (heightData[Convert.ToInt32(Math.Ceiling(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))] + (vertexData[i + 1] - Math.Floor(vertexData[i + 1])) / (Math.Ceiling(vertexData[i + 1]) - Math.Floor(vertexData[i + 1])) * (heightData[Convert.ToInt32(Math.Ceiling(vertexData[i])), Convert.ToInt32(Math.Ceiling(vertexData[i + 1]))] - heightData[Convert.ToInt32(Math.Ceiling(vertexData[i])), Convert.ToInt32(Math.Floor(vertexData[i + 1]))])) * a;
                            a = (c + d) / 2 * relativeheight * relativescale;
                            if (vertexData[i + 2] < a)
                            {
                                collision = true;
                                speedx = speedx - Math.Abs((a - vertexData[i + 2]) * speedx / 20) * dx * direction;
                                speedy = speedy - Math.Abs((a - vertexData[i + 2]) * speedy / 20) * dy * direction;
                            }
                            else
                                collision = false;
                        }
                        else
                            a = 0;

                    }
                }
            }
            
            

            //if (wheelposrfx > 15 & wheelposrfx < 35 & wheelposrfy > -5 & wheelposrfy < 15)
            //{
            //    floorrf = 0.2;
            //}
            //if (wheelposrbx > 15 & wheelposrbx < 35 & wheelposrby > -5 & wheelposrby < 15)            //collission 
            //{
            //    floorrb = 0.2;
            //}
            //if (wheelposlfx > 15 & wheelposlfx < 35 & wheelposlfy > -5 & wheelposlfy < 15)
            //{
            //    floorlf = 0.2;
            //}
            //if (wheelposlbx > 15 & wheelposlbx < 35 & wheelposlby > -5 & wheelposlby < 15)
            //{
            //    floorlb = 0.2;
            //}

            if (wheelposrfz < floorrf - 0.01)
            {
                //collisionfzrf = speedz * 0.6 + (wheelposrfz - floorrf) * speed;
                //dh = dh + (wheelposrfz - floorrf);
                pause2 = 0;
                wheelposrfz = floorrf;
                wheelspeedrfz = 0;
            }

            if (wheelposlfz < floorlf - 0.01)
            {
                //collisionfzlf = speedz * 0.6 + (wheelposlfz - floorlf) * speed;             //collision against wheels
                //dh = dh + (wheelposlfz - floorlf);
                pause2 = 0;
                wheelposlfz = floorlf;
                wheelspeedlfz = 0;
            }

            if (wheelposrbz < floorrb - 0.01)
            {
                //collisionfzrb = speedz * 0.6 + (wheelposrbz - floorrb) * speed;
                //dh = dh + (wheelposrbz - floorrb);
                pause2 = 0;
                wheelposrbz = floorrb;
                wheelspeedrbz = 0;
            }

            if (wheelposlbz < floorlb - 0.01)
            {
                //collisionfzlb = speedz * 0.6 + (wheelposlbz - floorlb) * speed;
                //dh = dh + (wheelposlbz - floorlb);
                pause2 = 0;
                wheelposlbz = floorlb;
                wheelspeedlbz = 0;
            }

            positionz = (wheelposrfz + wheelposlfz + wheelposrbz + wheelposlbz) / 4;
            speedz = (wheelspeedrfz + wheelspeedlfz + wheelspeedrbz + wheelspeedlbz) / 4;

            horizontalangle = Math.Asin(((wheelposlbz + wheelposlfz) / 2 - (wheelposrbz + wheelposrfz) / 2) / wheelbasewidth);



            slopeangle = Math.Asin(((wheelposlbz + wheelposrbz) / 2 - (wheelposrfz + wheelposlfz) / 2) / wheelbaselength);

            gravityacceleration = gravity * (slopeangle);




            if (KeyboardState.IsKeyUp(Keys.Space))
                rpm = (speed + spinftyrespeed * frontwheeldrive + spinrtyrespeed * (1 - frontwheeldrive)) * ratio * 60 / 2 / 3.14;

            if (KeyboardState.IsKeyDown(Keys.LeftShift) & Math.Abs(speed) < 8 & rpm < launchrpm)
                rpm = launchrpm;



            if (rpm < idlerpm)
                rpm = idlerpm;    // idle?




            if (KeyboardState.IsKeyDown(Keys.D1))            // camera
                camera = 1;

            if (KeyboardState.IsKeyDown(Keys.D2))            // camera
                camera = 2;

            if (KeyboardState.IsKeyDown(Keys.D3))            // camera
                camera = 3;

            if (KeyboardState.IsKeyDown(Keys.D4))            // camera
                camera = 4;

            if (KeyboardState.IsKeyDown(Keys.D5))            // camera
                camera = 5;

            if (KeyboardState.IsKeyDown(Keys.D6))            // camera
                camera = 6;

            if (KeyboardState.IsKeyDown(Keys.D7))            // camera
                camera = 7;

            if (KeyboardState.IsKeyDown(Keys.D8))            // camera
                camera = 8;



            if (KeyboardState.IsKeyDown(Keys.A))            // gearbox  
                if (pause > 10)
                    if (KeyboardState.IsKeyUp(Keys.Up) & MouseState.LeftButton == ButtonState.Released)          //upshift
                        if (KeyboardState.IsKeyDown(Keys.Space))
                            if (gear < gears + 1)
                            {
                                gear = gear + 1;
                                ratio = ratiovector[gear] / (wheelradiusfront * frontwheeldrive + wheelradiusrear * (1 - frontwheeldrive)) * finaldriveratio;
                                pause = 0;
                            }





            if (KeyboardState.IsKeyDown(Keys.Z))
                if (pause > 10)
                    if (KeyboardState.IsKeyUp(Keys.Up) & MouseState.LeftButton == ButtonState.Released)       //downshift
                        if (KeyboardState.IsKeyDown(Keys.Space))
                            if (gear > 0)
                            {
                                gear = gear - 1;
                                ratio = ratiovector[gear] / (wheelradiusfront * frontwheeldrive + wheelradiusrear * (1 - frontwheeldrive)) * finaldriveratio;
                                pause = 0;
                            }
            getengineparam();
            if (turbo == false & supercharger == false)
            {
                currentboost = 0;
                maxboost = 0;
            }
            else
                maxboost = lrpm.Y + (rpm - arpm) / 250 * (urpm.Y - lrpm.Y);    //extrapolation of engine parameters


            b = rpm;
            rpm = rpm - camangle;
            getengineparam();
            ve = lrpm.X + (rpm - arpm) / 250 * (urpm.X - lrpm.X);
            turbolag = lrpm.Z + (rpm - arpm) / 250 * (urpm.Z - lrpm.Z);

            pistonacceleration = stroke / 2000 * Math.Pow(2 * Math.PI * b / 60, 2);

            
            if (sportexhaust)
                ve = ve + 0.02;
            else if (racingexhaust)
                ve = ve + 0.04;
            if (racingmanifold)
                ve = ve + 0.03;
            if (cai)
                ve = ve + 0.01;
            if (ported)
                ve = ve + 0.02;
            if (racingexhaust & racingmanifold & cai & peakve < 0.95)
                ve = ve + 0.01;


            if (twinturbo)
                turbolag = turbolag * 0.6;
            if (supercharger)
                turbolag = 0.1;
            if (maxboost > enginerestriction.Y & enginerestriction.Y != 0)
                maxboost = enginerestriction.Y;
            if (currentboost < maxboost & KeyboardState.IsKeyDown(Keys.Up) & maxboost > 0 & turbolag > 0 & pause > shiftingtime * 60 / 4)           // turbo
                currentboost = currentboost + 1 / turbolag / 60;
            else if (currentboost < maxboost & MouseState.LeftButton == ButtonState.Pressed & maxboost > 0 & turbolag > 0 & pause > shiftingtime * 60 / 3.5)           // turbo
                currentboost = currentboost + 1 / turbolag / 60;
            else if (KeyboardState.IsKeyDown(Keys.Up)& currentboost >= maxboost)
                currentboost = maxboost;
            else if (MouseState.LeftButton == ButtonState.Pressed & currentboost >= maxboost)
                currentboost = maxboost;
            else if (currentboost > 0)
            {
                currentboost = currentboost * 0.97 - 0.03;
                if (pause4 > 30 & currentboost > 0)
                    bov.Play((float)(currentboost / 40),-0.4f,0f);
                pause4 = 0;
            }



            if (currentboost > 0 & currentboost < 5.6)
            {
                instance.Pitch = (float)(-1 + Math.Pow(currentboost, 0.8) / 2);
                instance.Volume = (float)(Math.Pow(currentboost, 0.85) / 40);
            }
            else
                instance.Volume = 0f;


            if (fuel == "petrol")
            {
                engineefficiency = 0.31 * Math.Pow(compression / 11, 0.2);
                if (ve * rpm / 60 * displacement / 1000 / stroketype > intakemax)         //intake limitation
                    ve = intakemax * 1000 * stroketype * 60 / displacement / rpm;
                if (enginerestriction.X < turbosize & enginerestriction.X != 0)
                    d = enginerestriction.X;
                else
                    d = turbosize;
                a = Math.Pow((d / 2), 2) * Math.PI / 3 * 0.95;  // a = cfm of turbo
                if (twinturbo)
                    a = a * 0.85;
                if ((ve + currentboost) * rpm / 60 * displacement / 1000 / stroketype > a / 2.119)            // turbo limitations
                {
                    e = currentboost;
                    currentboost = a / 2.119 / rpm * 60 / displacement * 1000 * stroketype - ve;
                    if (e < 5)
                    {
                        instance.Pitch = (float)(-1 + Math.Pow(e, 0.8) / 2);
                        instance.Volume = (float)(Math.Pow(e, 0.85) / 40);
                    }
                }
                if (currentboost < 0)
                    currentboost = 0;
                if (currentboost > turbomax)
                    currentboost = turbomax;
                if (ve * (1 + currentboost) * rpm / 60 * displacement / 1000 / stroketype * 1.45 > exhaustmax)
                    currentboost = exhaustmax * 1000 * stroketype * 60 / displacement / rpm / ve / 1.45 - 1;       //exhaust limitation     1.45: correcting factor for added fuel and exhaust temp
                if (pistonacceleration > 22000)
                    engineefficiency = engineefficiency * Math.Pow(22000 / pistonacceleration, pistonweight / 1.5);  // piston acceleration
                maxtorque = (ve * (currentboost + 1)) * displacement / 1000 / stroketype * 690 * engineefficiency;   //engine torque
                maxtorque = maxtorque * Math.Pow(12.5 / airfuelratio, 0.3);
                if (airfuelratio < 12.5)
                    maxtorque = maxtorque * (airfuelratio / 12.5);
                if (maxtorque > enginerestriction.Z & enginerestriction.Z != 0)
                    maxtorque = enginerestriction.Z;
                if (speed > speedlimiter & speedlimiter != 0)
                    maxtorque = 0;

                if (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 > injectorsize * 0.9)
                    maxtorque = maxtorque * 0.9 * injectorsize / (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771);   // injector limitation

                if (b > camlift)
                {
                    maxtorque = maxtorque * Math.Pow(camlift / b, 2.5);
                }
                if (b > camlift * 1.15)
                    maxtorque = 0;

                engineknock = false;
                e = 18;
                if (intercooler)
                    e = e + 2;
                if (variablesparkplug)
                    e = e + 7;
                if (waterinjection)
                    e = e + 10;
                else if (methanolinjection)
                    e = e + 12;

                e = e * Math.Pow(b / 5000,0.25) * 14.7 / airfuelratio * 10 / compression;         // knocking limitations
                e = e + (octane - 95) / 2;

                if ((1 + currentboost) * compression > e)
                {
                    engineknock = true;
                    maxtorque = maxtorque * 0.3;
                }

            }
            if (fuel == "diesel")
            {
                engineefficiency = 0.35 * Math.Pow(compression / 20, 0.2);
                if (ve * rpm / 60 * displacement / 1000 / stroketype > intakemax)         //intake limitation
                    ve = intakemax * 1000 * stroketype * 60 / displacement / rpm;
                if (enginerestriction.X < turbosize & enginerestriction.X != 0)
                    d = enginerestriction.X;
                else
                    d = turbosize;
                a = Math.Pow((d / 2), 2) * Math.PI / 3 * 0.95;  // a = cfm of turbo
                if (twinturbo)
                    a = a * 0.85;
                if ((ve + currentboost) * rpm / 60 * displacement / 1000 / stroketype > a / 2.119)          // turbolimitations
                    currentboost = a / 2.119 / rpm * 60 / displacement * 1000 * stroketype - ve;
                if (currentboost < 0)
                    currentboost = 0;
                if (currentboost > turbomax)
                    currentboost = turbomax;
                if (ve * (1 + currentboost) * rpm / 60 * displacement / 1000 / stroketype * 1.45 > exhaustmax)
                    currentboost = exhaustmax * 1000 * stroketype * 60 / displacement / rpm / ve / 1.45 - 1;       //exhaust limitation     1.45: correcting factor for added fuel and exhaust temp
                if (rpm > 3000)
                    engineefficiency = engineefficiency * Math.Pow(3000 / rpm, 0.6);   // because diesel is slow-burning
                if (pistonacceleration > 22000)
                    engineefficiency = engineefficiency * Math.Pow(22000 / pistonacceleration, pistonweight / 1.5);  // piston acceleration
                maxtorque = (ve * (currentboost + 1)) * displacement / 1000 / stroketype * 690 * engineefficiency;   //engine torque
                maxtorque = maxtorque * Math.Pow(12.5 / airfuelratio, 0.5);
                if (airfuelratio < 12.5)
                    maxtorque = maxtorque * (airfuelratio / 12.5);
                if (maxtorque > enginerestriction.Z & enginerestriction.Z != 0)
                    maxtorque = enginerestriction.Z;
                if (speed > speedlimiter & speedlimiter != 0)
                    maxtorque = 0;

                if (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771 > injectorsize * 0.9)
                    maxtorque = maxtorque * 0.9 * injectorsize / (ve * (1 + currentboost) * rpm * displacement / 1000 / stroketype / airfuelratio * 1.2 / 0.771);
            }

            rpm = b;

            

            if (KeyboardState.IsKeyUp(Keys.Space) & KeyboardState.IsKeyUp(Keys.LeftShift) & stationary == false)
                if (KeyboardState.IsKeyUp(Keys.Up) & MouseState.LeftButton == ButtonState.Released & Math.Abs(speed) > 0.1 & gas >= 0 & spinftyrespeed == 0 & spinrtyrespeed == 0)
                {
                    torque = -(displacement / 9) * rpm / 35000;           //compression 
                    if (ratio > 0 & speed < 0)
                        torque = -torque;
                }

            if (rpm > maxrpm & spinftyrespeed == 0 & spinrtyrespeed == 0)
                torque = -(displacement / 9) * rpm / 35000;
            if (rpm > maxrpm & spinftyrespeed > 0)
                spinftyrespeed = spinftyrespeed - (displacement / 9) * rpm / 35000 * wheelradiusfront / wheelmoif / 60;
            if (rpm > maxrpm & spinrtyrespeed > 0)
                spinrtyrespeed = spinrtyrespeed - (displacement / 9) * rpm / 35000 * wheelradiusrear / wheelmoir / 60;




            if (KeyboardState.IsKeyDown(Keys.Space))                 // clutch
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & rpm < maxrpm)
                {
                    gas = gas + 1;
                    torque = 0;
                    rpm = rpm + 100;
                }
                else
                {
                    gas = 0;
                    torque = 0;
                    rpm = rpm - 50;
                }
            }
            else if (KeyboardState.IsKeyDown(Keys.Space))
            {
                if (MouseState.LeftButton == ButtonState.Pressed & rpm < maxrpm)
                {
                    gas = gas + 1;
                    gaspedal = 1;
                    torque = 0;
                    rpm = rpm + 100;
                }
                else
                {
                    gas = 0;
                    torque = 0;
                    rpm = rpm - 50;
                    gaspedal = 0;
                }
            }




            if (controls == 1)
            {
                if (KeyboardState.IsKeyDown(Keys.Up) & pause > shiftingtime * 60 & rpm < maxrpm & menu == 1 & KeyboardState.IsKeyUp(Keys.Space) & go)             // gas pedal
                {
                    gas = gas + 1;
                    if (gaspedal < 1)
                        gaspedal = gaspedal + gaspedalsensitivity;
                    if (gaspedal > 1)
                        gaspedal = 1;
                    torque = maxtorque * friction * gaspedal;
                }
                else
                {
                    if (gaspedal > 0)
                        gaspedal = gaspedal - gaspedalsensitivity;
                    if (gaspedal < 0)
                        gaspedal = 0;
                    if (rpm < maxrpm & gaspedal > 0)
                        torque = maxtorque * friction * gaspedal;
                }
                if (KeyboardState.IsKeyDown(Keys.Space))
                    gaspedal = 0;
            }

            if (controls == 2)
            {
                if (MouseState.LeftButton == ButtonState.Pressed & pause > shiftingtime * 60 & rpm < maxrpm & menu == 1 & KeyboardState.IsKeyUp(Keys.Space) & go)             // gas pedal
                {
                    gas = gas + 1;
                    if (gaspedal < 1)
                        gaspedal = gaspedal + gaspedalsensitivity;
                    if (gaspedal > 1)
                        gaspedal = 1;
                    torque = maxtorque * friction * gaspedal;
                }
                else
                {
                    if (gaspedal > 0)
                        gaspedal = gaspedal - gaspedalsensitivity;
                    if (gaspedal < 0)
                        gaspedal = 0;
                    if (rpm < maxrpm & gaspedal > 0)
                        torque = maxtorque * friction * gaspedal;
                }
                if (KeyboardState.IsKeyDown(Keys.Space))
                    gaspedal = 0;
            }


            if ((KeyboardState.IsKeyDown(Keys.Down) || MouseState.RightButton == ButtonState.Pressed) & menu == 1)         // brake pedal
            {
                if (spinftyrespeed > 0 & direction == 1)
                    spinftyrespeed = spinftyrespeed - (griprf + griplf) * 5 / wheelmoif / 60;
                if (spinrtyrespeed > 0 & direction == 1)
                    spinrtyrespeed = spinrtyrespeed - (griprb + griplb) * 5 / wheelmoir / 60;
                if (spinftyrespeed < 0 & direction == -1)
                    spinftyrespeed = spinftyrespeed + (griprf + griplf) * 5 / wheelmoif / 60;
                if (spinrtyrespeed < 0 & direction == -1)
                    spinrtyrespeed = spinrtyrespeed + (griprb + griplb) * 5 / wheelmoir / 60;
                if (wheelposlbz < floorlb + 0.08)
                    acceleration = -griplb * 0.95 * direction;
                if (wheelposrbz < floorrb + 0.08)
                    acceleration = acceleration - griprb * 0.95 * direction;
                if (wheelposlfz < floorlf + 0.08)
                    acceleration = acceleration - griplf * 0.95 * direction;
                if (wheelposrfz < floorrf + 0.08)
                    acceleration = acceleration - griprf * 0.95 * direction;
                griprf = griprf * 0.3;
                griplf = griplf * 0.3;
                griplb = griplb * 0.3;
                griprb = griprb * 0.3;
            }
            else
                acceleration = 0;



            if (KeyboardState.IsKeyDown(Keys.U))
                positiony = 10;


            if (controls == 1)
            {
                if (KeyboardState.IsKeyDown(Keys.Left) & KeyboardState.IsKeyUp(Keys.Right) & rollover == false)         //steer left
                {
                    wheelangle = -wheelbaselength / turningradius;
                    if (steer * speed * direction <= -(griprb + griplb) * 2)
                    {
                        steer = steer + angularacceleration / 50;
                        angularacceleration = 0;
                    }
                    steer = steer - angularacceleration / 60;
                    if (Math.Abs(speed / steer) < (turningradius - wheelbasewidth) & steer < 0)
                    {
                        steer = -speed * direction / (turningradius - wheelbasewidth);
                    }
                }

                if (KeyboardState.IsKeyDown(Keys.Right) & KeyboardState.IsKeyUp(Keys.Left) & rollover == false)
                {
                    wheelangle = wheelbaselength / turningradius;
                    if (steer * speed * direction >= (griprb + griplb) * 2)
                    {
                        steer = steer - angularacceleration / 60;
                        angularacceleration = 0;                                            // steer  right
                    }
                    steer = steer + angularacceleration / 60;
                    if (Math.Abs(speed / steer) < turningradius & steer > 0)
                    {
                        steer = speed * direction / turningradius;
                    }
                }
                if (KeyboardState.IsKeyDown(Keys.Right) & KeyboardState.IsKeyDown(Keys.Left))
                    wheelangle = 0;
                if (KeyboardState.IsKeyUp(Keys.Right) & KeyboardState.IsKeyUp(Keys.Left))
                    wheelangle = 0;
            }

            if (stationary)
                steer = 0.001;
            if (controls == 2)
            {
                a = MouseState.X;
                wheelangle = (a - 840) / 2000;
                if (Math.Abs(wheelangle) < deadzone)
                    wheelangle = 0;
                if (speed > 10)
                    wheelangle = wheelangle * 10 / speed;
                a = wheelbaselength / wheelangle;
                a = speed * speed / a;
                if (wheelangle < 0 & rollover == false & stationary == false)         //steer left
                {
                    if (steer * speed * direction <= a)
                    {
                        steer = steer + angularacceleration / 50;
                        angularacceleration = 0;
                    }
                    if (steer * speed * direction <= -(griprb + griplb) * 2)
                    {
                        steer = steer + angularacceleration / 50;
                        angularacceleration = 0;
                        griplb = 0.2;
                        griprb = 0.2;
                        griplf = 0.2;
                        griprf = 0.2;
                    }
                    else
                    {
                        griplb = ((griprb + griplb) * 2 + steer * speed * direction) / 4;
                        griprb = ((griprb + griplb) * 2 + steer * speed * direction) / 4;
                        griplf = ((griprb + griplb) * 2 + steer * speed * direction) / 4;
                        griprf = ((griprb + griplb) * 2 + steer * speed * direction) / 4;
                        if (griplb < 0.2)
                            griplb = 0.2;
                        if (griprb < 0.2)
                            griprb = 0.2;
                        if (griplf < 0.2)
                            griplf = 0.2;
                        if (griprf < 0.2)
                            griprf = 0.2;
                    }
                    steer = steer - angularacceleration / 60;
                    if (Math.Abs(speed / steer) < (turningradius - wheelbasewidth) & steer < 0)
                    {
                        steer = -speed * direction / (turningradius - wheelbasewidth);
                    }
                }

                

                if (wheelangle > 0 & rollover == false & stationary == false)
                {
                    if (steer * speed * direction >= a)
                    {
                        steer = steer - angularacceleration / 50;
                        angularacceleration = 0;
                    }
                    if (steer * speed * direction >= (griprb + griplb) * 2)                 // steer  right
                    {
                        steer = steer - angularacceleration / 50;
                        angularacceleration = 0;
                        griplb = 0.2;
                        griprb = 0.2;
                        griplf = 0.2;
                        griprf = 0.2;
                    }
                    else
                    {
                        griplb = ((griprb + griplb) * 2 - steer * speed * direction) / 4;
                        griprb = ((griprb + griplb) * 2 - steer * speed * direction) / 4;
                        griplf = ((griprb + griplb) * 2 - steer * speed * direction) / 4;
                        griprf = ((griprb + griplb) * 2 - steer * speed * direction) / 4;
                        if (griplb < 0.2)
                            griplb = 0.2;
                        if (griprb < 0.2)
                            griprb = 0.2;
                        if (griplf < 0.2)
                            griplf = 0.2;
                        if (griprf < 0.2)
                            griprf = 0.2;
                    }
                    steer = steer + angularacceleration / 60;
                    if (Math.Abs(speed / steer) < turningradius & steer > 0)
                    {
                        steer = speed * direction / turningradius;
                    }
                }
            }



            if (Math.Abs(speed) > 8)
                gravitysteer = gravity * Math.Tan(horizontalangle) / speed;     // banked curve
            else if (Math.Abs(speed) > 5)
                gravitysteer = gravity * Math.Tan(horizontalangle) / speed / 2;     
            else if (Math.Abs(speed) > 3)
                gravitysteer = gravity * Math.Tan(horizontalangle) / speed / 3;     
            else gravitysteer = 0;




            if (controls == 1)
            {
                if (KeyboardState.IsKeyUp(Keys.Right) & KeyboardState.IsKeyUp(Keys.Left) & Math.Abs(steer) <= 0.1 & rollover == false)
                {
                    steer = steer * 0.96;
                }
                if (KeyboardState.IsKeyUp(Keys.Right) & KeyboardState.IsKeyUp(Keys.Left) & steer < -0.1)
                    steer = steer + angularacceleration / 60;
                else if (KeyboardState.IsKeyUp(Keys.Right) & KeyboardState.IsKeyUp(Keys.Left) & steer > 0.1)
                    steer = steer - angularacceleration / 60;
            }

            if (controls == 2)
            {
                if (wheelangle == 0 & Math.Abs(steer) <= 0.1 & rollover == false)
                {
                    steer = steer * 0.96;
                }
                if (wheelangle == 0 & steer < -0.1)
                    steer = steer + angularacceleration / 60;
                else if (wheelangle == 0 & steer > 0.1)
                    steer = steer - angularacceleration / 60;
            }


            loadtransferside = steer * speed * massheight / wheelbasewidth / gravity - Math.Sin(horizontalangle);





            mass = mass + wheelmoif + wheelmoir;

            drag = Cv * 1.2 / 2 * frontalarea * speed * speed / mass;              //drag=Cd*P*A/2*(v^2)/m
            rollingres = (0.02 + 3.24 * 0.002 * Math.Pow(Math.Abs(speed) / 32 + 0.1, 3.2)) * (tyrewidthf + tyrewidthr) / 2 / 0.22;

            acceleration = acceleration - drag * direction;

            if (direction == 1 & griprf != 0)
            {
                if (wheelposrfz < floorrf + 0.08 & Math.Abs(torque * frontwheeldrive / 2 * ratio / mass) <= griprf)
                {
                    acceleration = acceleration + (torque * frontwheeldrive / 2 * ratio / mass - rollingres / 4);
                    spinftyrespeed = spinftyrespeed * 0.99 - 0.1;
                    if (spinftyrespeed < 0.2)
                        spinftyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration + griprf * 0.85;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass > griprf)
                {
                    acceleration = acceleration + griprf * 0.85;
                    spinftyrespeed = spinftyrespeed + (torque * frontwheeldrive / 2 * ratio / mass / wheelradiusfront - griprf * 0.85) / wheelmoif / 60;        
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass < -griprf)
                {
                    acceleration = acceleration - griprf * 0.85;
                    spinftyrespeed = 0;      // if spin in other direction spin must be instantly stopped and force dumped onto wheels
                }


                if (wheelposlfz < floorlf + 0.08 & Math.Abs(torque * frontwheeldrive / 2 * ratio / mass) <= griplf)
                {
                    acceleration = acceleration + (torque * frontwheeldrive / 2 * ratio / mass - rollingres / 4);
                    spinftyrespeed = spinftyrespeed * 0.99 - 0.1;
                    if (spinftyrespeed < 0.2)
                        spinftyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration + griplf * 0.85;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass > griplf)
                {
                    acceleration = acceleration + griplf * 0.85;
                    spinftyrespeed = spinftyrespeed + (torque * frontwheeldrive / 2 * ratio / mass / wheelradiusfront - griplf * 0.85) / wheelmoif / 60;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass < -griplf)
                {
                    acceleration = acceleration - griplf * 0.85;
                    spinftyrespeed = 0;
                }

                if (wheelposrbz < floorrb + 0.08 & Math.Abs(torque * (1 - frontwheeldrive) / 2 * ratio / mass) <= griprb)
                {
                    acceleration = acceleration + (torque * (1 - frontwheeldrive) / 2 * ratio / mass - rollingres / 4);   //steerforce * wheelbaselength * (1 - frontweight) / momentofinertia
                    spinrtyrespeed = spinrtyrespeed * 0.99 - 0.1;
                    if (spinrtyrespeed < 0.2)
                        spinrtyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration + griprb * 0.85;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass > griprb)
                {
                    acceleration = acceleration + griprb * 0.85;
                    spinrtyrespeed = spinrtyrespeed + (torque * (1 - frontwheeldrive) / 2 * ratio / mass / wheelradiusrear - griprb * 0.85) / wheelmoir / 60;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass < -griprb)
                {
                    acceleration = acceleration - griprb * 0.85;
                    spinrtyrespeed = 0;
                }


                if (wheelposlbz < floorlb + 0.08 & Math.Abs(torque * (1 - frontwheeldrive) / 2 * ratio / mass) <= griplb)
                {
                    acceleration = acceleration + (torque * (1 - frontwheeldrive) / 2 * ratio / mass - rollingres / 4);
                    spinrtyrespeed = spinrtyrespeed * 0.99 - 0.1;
                    if (spinrtyrespeed < 0.2)
                        spinrtyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration + griplb * 0.85;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass > griplb)
                {
                    acceleration = acceleration + griplb * 0.85;
                    spinrtyrespeed = spinrtyrespeed + (torque * (1 - frontwheeldrive) / 2 * ratio / mass / wheelradiusrear - griplb * 0.85) / wheelmoir / 60;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass < -griplb)
                {
                    acceleration = acceleration - griplb * 0.85;
                    spinrtyrespeed = 0;
                }
            }

            if (direction == -1 & griprf != 0)
            {
                if (wheelposrfz < floorrf + 0.08 & Math.Abs(torque * frontwheeldrive / 2 * ratio / mass) <= griprf * 0.9)
                {
                    acceleration = acceleration + (torque * frontwheeldrive / 2 * ratio / mass + rollingres / 4);
                    spinftyrespeed = spinftyrespeed * 0.99 + 0.1;
                    if (spinftyrespeed > -0.2)
                        spinftyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration - griprf * 0.85;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass > griprf)
                {
                    acceleration = acceleration + griprf * 0.85;
                    spinftyrespeed = 0;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass < -griprf)
                {
                    acceleration = acceleration - griprf * 0.85;
                    spinftyrespeed = spinftyrespeed + (torque * frontwheeldrive / 2 * ratio / mass / wheelradiusrear + griprf * 0.85) / wheelmoif / 60;
                }


                if (wheelposlfz < floorlf + 0.08 & Math.Abs(torque * frontwheeldrive / 2 * ratio / mass) <= griplf)
                {
                    acceleration = acceleration + (torque * frontwheeldrive / 2 * ratio / mass + rollingres / 4);
                    spinftyrespeed = spinftyrespeed * 0.99 + 0.1;
                    if (spinftyrespeed > -0.2)
                        spinftyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration - griplf * 0.85;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass > griplf)
                {
                    acceleration = acceleration + griplf * 0.85;
                    spinftyrespeed = 0;
                }
                else if (torque * frontwheeldrive / 2 * ratio / mass < -griplf)
                {
                    acceleration = acceleration - griplf * 0.85;
                    spinftyrespeed = spinftyrespeed + (torque * frontwheeldrive / 2 * ratio / mass / wheelradiusfront + griplf * 0.85) / wheelmoif / 60;
                }

                if (wheelposrbz < floorrb + 0.08 & Math.Abs(torque * (1 - frontwheeldrive) / 2 * ratio / mass) <= griprb)
                {
                    acceleration = acceleration + (torque * (1 - frontwheeldrive) / 2 * ratio / mass + rollingres / 4);
                    spinrtyrespeed = spinrtyrespeed * 0.99 + 0.1;
                    if (spinrtyrespeed > -0.2)
                        spinrtyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration - griprb * 0.85;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass > griprb)
                {
                    acceleration = acceleration + griprb * 0.85;
                    spinrtyrespeed = 0;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass < -griprb)
                {
                    acceleration = acceleration - griprb * 0.85;
                    spinrtyrespeed = spinrtyrespeed + (torque * (1 - frontwheeldrive) / 2 * ratio / mass / wheelradiusrear + griprb * 0.85) / wheelmoir / 60;
                }


                if (wheelposlbz < floorlb + 0.08 & Math.Abs(torque * (1 - frontwheeldrive) / 2 * ratio / mass) <= griplb)
                {
                    acceleration = acceleration + (torque * (1 - frontwheeldrive) / 2 * ratio / mass + rollingres / 4);
                    spinrtyrespeed = spinrtyrespeed * 0.99 + 0.1;
                    if (spinrtyrespeed > -0.2)
                        spinrtyrespeed = 0;
                    else if (torque <= 0)
                        acceleration = acceleration - griplb * 0.85;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass > griplb)
                {
                    acceleration = acceleration + griplb * 0.85;
                    spinrtyrespeed = 0;
                }
                else if (torque * (1 - frontwheeldrive) / 2 * ratio / mass < -griplb)
                {
                    acceleration = acceleration - griplb * 0.85;
                    spinrtyrespeed = spinrtyrespeed + (torque * (1 - frontwheeldrive) / 2 * ratio / mass / wheelradiusrear + griplb * 0.85) / wheelmoir / 60;
                }
            }

            

            mass = mass - wheelmoif - wheelmoir;





            if ((springlbspeed + springrbspeed) / 2 < 0 & acceleration > 1)
                acceleration = acceleration + (springlbspeed + springrbspeed);







            loadtransfer = acceleration * massheight / wheelbaselength / gravity - Math.Sin(slopeangle);
            




            speed = Math.Pow(speedx * speedx + speedy * speedy, 0.5) * direction;             // calculate velocity



            if (stationary == false & Math.Abs(speed) > 0)                            // divide by zero problem fix
            {
                dx = speedx / speed;
                dy = speedy / speed;
            }
            




            if (dy > 0 & dx < 0)                      //calculate rotation of model in the x/y-plane
                angle = -Math.Asin(dx);
            if (dy < 0 & dx < 0)
                angle = Math.PI / 2 - Math.Asin(dy);
            if (dy < 0 & dx > 0)
                angle = Math.PI + Math.Asin(dx);
            if (dy > 0 & dx > 0)
                angle = Math.PI * 3 / 2 + Math.Asin(dy);

            driftangle = driftangle + driftanglespeed / 60;

            dxp = dx * Math.Cos(driftangle) - dy * Math.Sin(driftangle);
            dyp = dx * Math.Sin(driftangle) + dy * Math.Cos(driftangle);

            if (wheelposrfz < floorrf + 10)
                springrfspeed = springrfspeed - springstiffnessf * springrfpos / mass / 60 - gravity / 2 * frontweight / 60 * (1 + loadtransferside) * (1 - loadtransfer);         //suspension 
            if (pause2 <= 10)
                springrfspeed = springrfspeed + collisionfzlf / 2 - collisionfzrb / 2 + collisionfzrb / 4 + collisionfzrf / 4 + collisionfzlf / 4 + collisionfzlb / 4;
            springrfspeed = springrfspeed * springdampingf;

            //left front

            if (wheelposrbz < floorrb + 10)
                springrbspeed = springrbspeed - springstiffnessb * springrbpos / mass / 60 - gravity / 2 * (1 - frontweight) / 60 * (1 + loadtransferside) * (1 + loadtransfer);         //suspension
            if (pause2 <= 10)
                springrbspeed = springrbspeed + collisionfzlb / 2 - collisionfzrf / 2 + collisionfzrb / 4 + collisionfzrf / 4 + collisionfzlf / 4 + collisionfzlb / 4;
            springrbspeed = springrbspeed * springdampingb;

            //left back




            if (wheelposlfz < floorlf + 10)
                springlfspeed = springlfspeed - springstiffnessf * springlfpos / mass / 60 - gravity / 2 * frontweight / 60 * (1 - loadtransferside) * (1 - loadtransfer);         //suspension 
            if (pause2 <= 10)
                springlfspeed = springlfspeed + collisionfzrf / 2 - collisionfzlb / 2 + collisionfzrb / 4 + collisionfzrf / 4 + collisionfzlf / 4 + collisionfzlb / 4;
            springlfspeed = springlfspeed * springdampingf;

            // right front

            if (wheelposlbz < floorlb + 10)
                springlbspeed = springlbspeed - springstiffnessb * springlbpos / mass / 60 - gravity / 2 * (1 - frontweight) / 60 * (1 - loadtransferside) * (1 + loadtransfer);         //suspension 
            if (pause2 <= 10)
                springlbspeed = springlbspeed + collisionfzrb / 2 - collisionfzlf / 2 + collisionfzrb / 4 + collisionfzrf / 4 + collisionfzlf / 4 + collisionfzlb / 4;                                       //right back
            springlbspeed = springlbspeed * springdampingb;

            springrfpos = springrfpos + springrfspeed / 60;
            springrbpos = springrbpos + springrbspeed / 60;
            springlfpos = springlfpos + springlfspeed / 60;
            springlbpos = springlbpos + springlbspeed / 60;


            //calculate available grip on each wheel

            if (-springrfpos * springstiffnessf / tyrewidthf > 4 * 22300)
                griprf = 22300 * tyrewidthf * tyrewidthf / mass * tyrebasegrip + Math.Pow((3 * 22300 * tyrewidthf), 0.85) / mass * tyrebasegrip * tyrewidthf;
            else if (-springrfpos * springstiffnessf / tyrewidthf > 22300)
                griprf = 22300 * tyrewidthf * tyrewidthf / mass * tyrebasegrip + Math.Pow((-springrfpos * springstiffnessf - 22300 * tyrewidthf), 0.85) / mass * tyrebasegrip * tyrewidthf;
            else
                griprf = -springrfpos * springstiffnessf / mass * tyrebasegrip * tyrewidthf;

            if (-springlfpos * springstiffnessf / tyrewidthf > 4 * 22300)
                griplf = 22300 * tyrewidthf * tyrewidthf / mass * tyrebasegrip + Math.Pow((3 * 22300 * tyrewidthf), 0.85) / mass * tyrebasegrip * tyrewidthf;
            else if (-springlfpos * springstiffnessf / tyrewidthf > 22300)
                griplf = 22300 * tyrewidthf * tyrewidthf / mass * tyrebasegrip + Math.Pow((-springlfpos * springstiffnessf - 22300 * tyrewidthf), 0.85) / mass * tyrebasegrip * tyrewidthf;
            else
                griplf = -springlfpos * springstiffnessf / mass * tyrebasegrip * tyrewidthf;

            if (-springrbpos * springstiffnessb / tyrewidthr > 4 * 22300)
                griprb = 22300 * tyrewidthr * tyrewidthr / mass * tyrebasegrip + Math.Pow((3 * 22300 * tyrewidthr), 0.85) / mass * tyrebasegrip * tyrewidthr;
            else if (-springrbpos * springstiffnessb / tyrewidthr > 22300)
                griprb = 22300 * tyrewidthr * tyrewidthr / mass * tyrebasegrip + Math.Pow((-springrbpos * springstiffnessb - 22300 * tyrewidthr), 0.85) / mass * tyrebasegrip * tyrewidthr;
            else
                griprb = -springrbpos * springstiffnessb / mass * tyrebasegrip * tyrewidthr;

            if (-springlbpos * springstiffnessb / tyrewidthr > 4 * 22300)
                griplb = 22300 * tyrewidthr * tyrewidthr / mass * tyrebasegrip + Math.Pow((3 * 22300 * tyrewidthr), 0.85) / mass * tyrebasegrip * tyrewidthr;
            else if (-springlbpos * springstiffnessb / tyrewidthr > 22300)
                griplb = 22300 * tyrewidthr * tyrewidthr / mass * tyrebasegrip + Math.Pow((-springlbpos * springstiffnessb - 22300 * tyrewidthr), 0.85) / mass * tyrebasegrip * tyrewidthr;
            else
                griplb = -springlbpos * springstiffnessb / mass * tyrebasegrip * tyrewidthr;






            steerforce = (griprf + griplf) * mass * wheelbaselength / 2;


            angularacceleration = steerforce * wheelbaselength * (1 - frontweight) / momentofinertia;


            xangle = Math.Asin((springrfpos - springrbpos) / wheelbaselength);
            yangle = Math.Asin((springlfpos - springlbpos) / wheelbaselength);

            x2angle = Math.Asin((springlfpos - springrfpos) / wheelbasewidth);
            y2angle = Math.Asin((springlbpos - springrbpos) / wheelbasewidth);

            acceleration = acceleration + gravityacceleration;


            if (rollover == false & stationary == false)
                speedx = acceleration / 60 * dx + speedx * Math.Cos(-(steer * direction + gravitysteer) / 60) - speedy * Math.Sin(-(steer * direction + gravitysteer) / 60);         //apply x-y accelerations to model

            if (rollover == false & stationary == false)
                speedy = acceleration / 60 * dy + speedx * Math.Sin(-(steer * direction + gravitysteer) / 60) + speedy * Math.Cos(-(steer * direction + gravitysteer) / 60);

            if (stationary)
                if (acceleration > rollingres)
                {
                    stationary = false;
                    direction = 1;
                }
            if (stationary == false & Math.Abs(speed) < 0.2 & direction == 1 & acceleration < rollingres)
            {
                stationary = true;
                speedx = 0;
                speedy = 0;
                speed = 0;
                acceleration = 0;
            }
            if (stationary)
                if (acceleration < -rollingres * 2)
                {
                    stationary = false;
                    direction = -1;
                }
            if (stationary == false & Math.Abs(speed) < 0.2 & direction == -1 & acceleration > -rollingres * 2)
            {
                stationary = true;
                speedx = 0;
                speedy = 0;
                speed = 0;
                acceleration = 0;
            }




            if (wheelposrfz > floorrf)
                wheelspeedrfz = wheelspeedrfz - gravity / 60;
            if (wheelposlfz > floorlf)
                wheelspeedlfz = wheelspeedlfz - gravity / 60;             //apply z acceleration to model (gravity)
            if (wheelposrbz > floorrb)
                wheelspeedrbz = wheelspeedrbz - gravity / 60;
            if (wheelposlbz > floorlb)
                wheelspeedlbz = wheelspeedlbz - gravity / 60;



            positionx = positionx + speedx / 60 * Math.Cos(slopeangle);                               // apply traslations to model
            positiony = positiony + speedy / 60 * Math.Cos(slopeangle);
            positionz = positionz + speedz / 60;

            wheelposrfx = positionx + wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) + wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposrfy = positiony - wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) + wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposrbx = positionx + wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) - wheelbaselength / 2 * dx * Math.Cos(slopeangle);                // calculate position of each wheel Again
            wheelposrby = positiony - wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) - wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposlfx = positionx - wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) + wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposlfy = positiony + wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) + wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposlbx = positionx - wheelbasewidth / 2 * dy * Math.Cos(horizontalangle) - wheelbaselength / 2 * dx * Math.Cos(slopeangle);
            wheelposlby = positiony + wheelbasewidth / 2 * dx * Math.Cos(horizontalangle) - wheelbaselength / 2 * dy * Math.Cos(slopeangle);

            wheelposrfz = wheelposrfz + wheelspeedrfz / 60;
            wheelposlfz = wheelposlfz + wheelspeedlfz / 60;
            wheelposrbz = wheelposrbz + wheelspeedrbz / 60;
            wheelposlbz = wheelposlbz + wheelspeedlbz / 60;

            //if (Math.Abs(steer * speed) > gravity * (((wheelbasewidth + (tyrewidthf / 2 + tyrewidthr / 2))) - Math.Sin(Math.Abs(y2angle))) / 2 / massheight)        //rollover check
            //    rollover = true;

            //if (Math.Abs(horizontalangle) >Math.Atan(wheelbasewidth / massheight))        //rollover check
            //     rollover = true;
            if (rollover & rollangle < Math.PI)
            {
                rollangle = rollangle + 0.1;
                speedx = 0;
                speedy = 0;
                speedz = 0;
                positionz = 1 / 10 / Math.PI;
            }
            else if (rollover)
            {
                speedx = 0;
                speedy = 0;
                speedz = 0;
            }

            
            tyredistancef = tyredistancef + speed / 60 + spinftyrespeed / 60;
            tyredistancer = tyredistancer + speed / 60 + spinrtyrespeed / 60;



            worldwheelrf = Matrix.CreateScale((float)(tyrewidthf / 0.22), (float)(wheelradiusfront / 0.3), (float)(wheelradiusfront / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationZ((float)(Math.PI)) * Matrix.CreateRotationX((float)(-tyredistancef / wheelradiusfront)) * Matrix.CreateRotationY((float)(horizontalangle)) * Matrix.CreateRotationZ((float)(angle + driftangle - wheelangle)) * Matrix.CreateTranslation(new Vector3((float)wheelposrfx, (float)wheelposrfy, (float)(wheelposrfz + wheelradiusfront)));  //apply
            worldwheellf = Matrix.CreateScale((float)(tyrewidthf / 0.22), (float)(wheelradiusfront / 0.3), (float)(wheelradiusfront / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationX((float)(-tyredistancef / wheelradiusfront)) * Matrix.CreateRotationY((float)(horizontalangle)) * Matrix.CreateRotationZ((float)(angle + driftangle - wheelangle)) * Matrix.CreateTranslation(new Vector3((float)wheelposlfx, (float)wheelposlfy, (float)(wheelposlfz + wheelradiusfront)));  //apply
            worldwheelrb = Matrix.CreateScale((float)(tyrewidthr / 0.22), (float)(wheelradiusrear / 0.3), (float)(wheelradiusrear / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationZ((float)(Math.PI)) * Matrix.CreateRotationX((float)(-tyredistancer / wheelradiusrear)) * Matrix.CreateRotationY((float)(horizontalangle)) * Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)wheelposrbx, (float)wheelposrby, (float)(wheelposrbz + wheelradiusrear)));  //apply 
            worldwheellb = Matrix.CreateScale((float)(tyrewidthr / 0.22), (float)(wheelradiusrear / 0.3), (float)(wheelradiusrear / 0.3)) * Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Matrix.CreateRotationX((float)(-tyredistancer / wheelradiusrear)) * Matrix.CreateRotationY((float)(horizontalangle)) * Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)wheelposlbx, (float)wheelposlby, (float)(wheelposlbz + wheelradiusrear)));  //apply
            worldspringrf = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposrfx - tyrewidthf * dy / 2), (float)(wheelposrfy + tyrewidthf * dx / 2), (float)(wheelposrfz + 0.7)));  //apply
            worldspringlf = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposlfx + tyrewidthf * dy / 2), (float)(wheelposlfy - tyrewidthf * dx / 2), (float)(wheelposlfz + 0.7)));  //apply
            worldspringrb = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposrbx - tyrewidthr * dy / 2), (float)(wheelposrby + tyrewidthr * dx / 2), (float)(wheelposrbz + 0.7)));  //apply 
            worldspringlb = Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateTranslation(new Vector3((float)(wheelposlbx + tyrewidthr * dy / 2), (float)(wheelposlby - tyrewidthr * dx / 2), (float)(wheelposlbz + 0.7)));  //apply
            if (camera == 1)
            {
                cameraposition = new Vector3((float)positionx - (float)dx * 7, (float)positiony - (float)dy * 7, (float)positionz + 2);
                cameradirection = new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)positionx - (float)dx * 7, (float)positiony - (float)dy * 7, (float)positionz + 2), new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz), new Vector3((float)dx, (float)dy, 0));
            }
            else if (camera == 2)
            {
                cameraposition = new Vector3((float)positionx - (float)dx * 2, (float)positiony - (float)dy * 2, (float)(positionz + 1.5));
                cameradirection = new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)positionx - (float)dx * 2, (float)positiony - (float)dy * 2, (float)(positionz + 1.5)), new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz), new Vector3((float)dx, (float)dy, 0));
            }
            else if (camera == 3)
            {
                cameraposition = new Vector3(5, 5, 3);
                cameradirection = new Vector3((float)(positionx), (float)(positiony), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)5, (float)5, (float)3), new Vector3((float)(positionx), (float)(positiony), (float)positionz), new Vector3(0, 0, 1));
            }
            else if (camera == 4)
            {
                cameraposition = new Vector3((float)positionx + (float)dx * 1, (float)positiony + (float)dy * 1, (float)(positionz + 1));
                cameradirection = new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)positionx + (float)dx * 1, (float)positiony + (float)dy * 1, (float)(positionz + 1)), new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz), new Vector3((float)dx, (float)dy, 0));
            }
            else if (camera == 5)
            {
                cameraposition = new Vector3((float)positionx - (float)dy * 5, (float)positiony + (float)dx * 5, (float)(positionz + 1.5));
                cameradirection = new Vector3((float)(positionx), (float)(positiony), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)positionx - (float)dy * 5, (float)positiony + (float)dx * 5, (float)(positionz + 1.5)), new Vector3((float)(positionx), (float)(positiony), (float)positionz), new Vector3((float)dy, -(float)dx, 0));
            }
            else if (camera == 6)
            {
                cameraposition = new Vector3((float)positionx + (float)dx * camerapos.X, (float)positiony + (float)dy * camerapos.Y, (float)positionz + camerapos.Z);
                cameradirection = new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)positionx + (float)dx * camerapos.X, (float)positiony + (float)dy * camerapos.Y, (float)positionz + camerapos.Z), new Vector3((float)(positionx + 10 * dx), (float)(positiony + 10 * dy), (float)positionz), new Vector3((float)dx, (float)dy, 0));
            }
            else if (camera == 7)
            {
                cameraposition = new Vector3(-40, 45, 3);
                cameradirection = new Vector3((float)(positionx), (float)(positiony), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)-40, (float)45, (float)3), new Vector3((float)(positionx), (float)(positiony), (float)positionz), new Vector3(0, 0, 1));
            }
            else if (camera == 8)
            {
                cameraposition = new Vector3(-40, 438, 5);
                cameradirection = new Vector3((float)(positionx), (float)(positiony), (float)positionz);
                view = Matrix.CreateLookAt(new Vector3((float)-40, (float)438, (float)5), new Vector3((float)(positionx), (float)(positiony), (float)positionz), new Vector3(0, 0, 1));
            }
            world0 = Matrix.CreateTranslation(0, 0, 0) * Matrix.CreateRotationY((float)rollangle) * Matrix.CreateRotationZ((float)(angle + driftangle)) * Matrix.CreateRotationX((float)((xangle - slopeangle) * dyp)) * Matrix.CreateRotationY((float)((xangle - slopeangle) * -dxp)) * Matrix.CreateRotationY((float)((y2angle - horizontalangle) * -dyp)) * Matrix.CreateRotationX((float)((y2angle - horizontalangle) * -dxp)) * Matrix.CreateTranslation((float)(positionx + offsetlength * dx - Math.Sin(slopeangle) * (wheelradiusfront + wheelradiusrear) / 2 * wheelbaselength / 2 * dx - Math.Sin(horizontalangle) * (wheelradiusfront + wheelradiusrear) / 2 * wheelbasewidth / 2 * dy), (float)(positiony + offsetlength * dy - Math.Sin(slopeangle) * (wheelradiusfront + wheelradiusrear) / 2 * wheelbaselength / 2 * dy - Math.Sin(horizontalangle) * (wheelradiusfront + wheelradiusrear) / 2 * wheelbasewidth / 2 * dx), (float)(positionz + (springrfpos + springrbpos + springlfpos + springlbpos) / 4 + offsetheight));
            cameradirection = cameradirection - cameraposition;
            

            pause = pause + 1;
            pause2 = pause2 + 1;
            pause3 = pause3 + 1;
            pause4 = pause4 + 1;
            if (go)
                time = time + 1;
            else if (time > 0 & go == false)
            {
                time = -440;
                if (checkpointx[0] == -56)
                    opponent = 1;          
            }
            else
                time = time + 1;

            if (time == 0)
            {
                go = true;
            }
            
            distance = distance + Math.Abs(speed) / 60;


            positionvector = new Vector3((float)positionx, (float)positiony, (float)positionz);
            

            if (speed * 3.6 >= 80 & trap1 == 0)
                trap1 = time / 60;
            if (speed * 3.6 >= 100 & trap2 == 0)
                trap2 = time / 60;
            if (speed * 3.6 >= 160 & trap3 == 0)
                trap3 = time / 60;
            if (distance >= 402 & trap4 == 0)
                trap4 = time / 60;

            while (_instance.PendingBufferCount < 3 & menu == 1)
                SubmitBuffer();

            if (lol == false)
            {
                instance.Play();
                instance.Volume = 0f;
            }
            lol = true;
            

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
            GraphicsDevice.RasterizerState = RasterizerState.CullNone;



            device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0);
            DrawTerrain(view);
            
            

            GraphicsDevice.BlendState = BlendState.AlphaBlend;

            DrawModel(garage, worldgarage, view, projection);
            DrawModel(portal, worldgarage, view, projection);
            DrawModel(garage, worldgarage2, view, projection);
            DrawModel(portal, worldgarage2, view, projection);
            for (int i = 0; i < carshoppositionx.Length; i++)
            {
                DrawModel(junkyard, Matrix.CreateTranslation(carshoppositionx[i], carshoppositiony[i], carshoppositionz[i]), view, projection);
                DrawModel(portal, Matrix.CreateTranslation(carshoppositionx[i], carshoppositiony[i] - 2, carshoppositionz[i]), view, projection);
            }
            for (int i = 0; i < partshoppositionx.Length; i++)
            {
                DrawModel(garage, Matrix.CreateTranslation(partshoppositionx[i], partshoppositiony[i], partshoppositionz[i]), view, projection);
                DrawModel(portal, Matrix.CreateTranslation(partshoppositionx[i], partshoppositiony[i], partshoppositionz[i]), view, projection);
            }

            if (checkpointx.Length > 1 & positionx > 0 & finish == false)
            {
                for (int i = checkpoint; i < checkpointx.Length - 1; i++)
                    DrawModel(portal, Matrix.CreateTranslation((float)checkpointx[i], (float)checkpointy[i], heightData[checkpointx[i], checkpointy[i]]), view, projection);
            }
            else if (checkpointx.Length > 1 & positionx <= 0 & finish == false)
            {
                for (int i = 0; i < checkpointx.Length - 1; i++)
                    DrawModel(portal, Matrix.CreateTranslation((float)checkpointx[i], (float)checkpointy[i], 0), view, projection);
            }
            DrawModel(dynomodel, Matrix.CreateTranslation(-22, 22, 0), view, projection);
            DrawModel(modelspring, worldspringrf, view, projection);
            DrawModel(modelspring, worldspringlb, view, projection);
            DrawModel(modelspring, worldspringlf, view, projection);
            DrawModel(modelspring, worldspringrb, view, projection);

            DrawModel(wheelfront, worldwheelrf, view, projection);
            DrawModel(wheelrear, worldwheellb, view, projection);
            DrawModel(wheelfront, worldwheellf, view, projection);
            DrawModel(wheelrear, worldwheelrb, view, projection);
            if (positiony > 600)
            {
                DrawModel(dragstrip, Matrix.CreateScale(new Vector3(1.2f, 1f, 1f)) * Matrix.CreateTranslation(new Vector3((float)-52.5, (float)(40 + 256 * (Math.Floor(positiony / 256f) - 1)), (float)-0.045)), view, projection);
                DrawModel(dragstrip, Matrix.CreateScale(new Vector3(1.2f, 1f, 1f)) * Matrix.CreateTranslation(new Vector3((float)-52.5, (float)(40 + 597.4 + 256 * (Math.Floor(positiony / 256f) - 1)), (float)-0.045)), view, projection);
            }
            else if (positiony > -300)
            {
                DrawModel(dragstrip, Matrix.CreateScale(new Vector3(1.2f, 1f, 1f)) * Matrix.CreateTranslation(new Vector3((float)-52.5, 40, (float)-0.045)), view, projection);
                DrawModel(dragstrip, Matrix.CreateScale(new Vector3(1.2f, 1f, 1f)) * Matrix.CreateTranslation(new Vector3((float)-52.5, (float)(40 + 597.4), (float)-0.045)), view, projection);
            }
            DrawModel(ground, worldground, view, projection);


            if (opponent != 0)
            {
                DrawModel(wheelfront2, worldwheelrf2, view, projection);
                DrawModel(wheelrear2, worldwheellb2, view, projection);
                DrawModel(wheelfront2, worldwheellf2, view, projection);
                DrawModel(wheelrear2, worldwheelrb2, view, projection);
                DrawModel(model2, world02, view, projection);
            }


            DrawModel(model, world0, view, projection);
            //DrawModel(collisionmodel, world0, view, projection);

            GraphicsDevice.BlendState = BlendState.Additive;
            DrawBillboard();
            
            spriteBatch.Begin();

            spriteBatch.Draw(kmh, new Vector2(200, 780), Color.White);
            spriteBatch.Draw(rpmgauge, new Vector2(500, 780), Color.White);
            spriteBatch.Draw(boost, new Vector2(750, 780), Color.White);


            Rectangle sourceRectangle = new Rectangle(0, 0, 4, 100);
            spriteBatch.Draw(needlered, new Vector2(328, 908), sourceRectangle, Color.White, (float)(0.63 + speed * 3.6 / 337 * 6.28), new Vector2(0, -20), 1f, SpriteEffects.None, 1);
            spriteBatch.Draw(needlered, new Vector2(628, 908), sourceRectangle, Color.White, (float)(1.62 + rpm / 2245), new Vector2(0, -20), 1f, SpriteEffects.None, 1);
            spriteBatch.Draw(needlered, new Vector2(810, 840), sourceRectangle, Color.White, (float)(1.62 + currentboost / 4.13 * 6.28), new Vector2(0, -2), 0.6f, SpriteEffects.None, 1);

            if (menu == 2.1)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, "Rocky pass", new Vector2(260, 400), Color.BlueViolet);
                spriteBatch.DrawString(font, "River basin", new Vector2(260, 440), Color.BlueViolet);
                spriteBatch.DrawString(font, "hillsbrad", new Vector2(260, 480), Color.BlueViolet);
                spriteBatch.DrawString(font, "cliffs", new Vector2(260, 520), Color.BlueViolet);
            }
            if (menu == 2.2)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, "drag challange - 402 m", new Vector2(260, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "drag challange 1000 m", new Vector2(260, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "2500cc stock class", new Vector2(460, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "fwd tuner class", new Vector2(460, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "test", new Vector2(460, 260), Color.BlueViolet);
            }
            if (menu == 3)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                if (randomvector[0] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name1, new Vector2(260, 220), Color.BlueViolet);
                if (randomvector[1] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name2, new Vector2(260, 240), Color.BlueViolet);
                
                if (randomvector[2] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name3, new Vector2(260, 260), Color.BlueViolet);
                
                if (randomvector[3] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name4, new Vector2(260, 280), Color.BlueViolet);
                
                if (randomvector[4] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name5, new Vector2(260, 300), Color.BlueViolet);
                
                if (randomvector[5] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name6, new Vector2(260, 320), Color.BlueViolet);
                
                if (randomvector[6] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name7, new Vector2(260, 340), Color.BlueViolet);
                
                if (randomvector[7] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name8, new Vector2(260, 360), Color.BlueViolet);
                
                if (randomvector[8] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name9, new Vector2(260, 380), Color.BlueViolet);
                
                if (randomvector[9] < 0.3)
                    spriteBatch.DrawString(font, currentcarshop.name10, new Vector2(260, 400), Color.BlueViolet);
                
                if (randomvector[10] < 0.2)
                    spriteBatch.DrawString(font, currentcarshop.name11, new Vector2(260, 420), Color.BlueViolet);
                
                if (randomvector[11] < 0.2)
                    spriteBatch.DrawString(font, currentcarshop.name12, new Vector2(260, 440), Color.BlueViolet);
                
                if (randomvector[12] < 0.2)
                    spriteBatch.DrawString(font, currentcarshop.name13, new Vector2(260, 460), Color.BlueViolet);
                
                if (randomvector[13] < 0.2)
                    spriteBatch.DrawString(font, currentcarshop.name14, new Vector2(260, 480), Color.BlueViolet);
                
                if (randomvector[14] < 0.2)
                    spriteBatch.DrawString(font, currentcarshop.name15, new Vector2(260, 500), Color.BlueViolet);          

                if (randomvector[15] < 0.1)
                    spriteBatch.DrawString(font, currentcarshop.name16, new Vector2(260, 520), Color.BlueViolet);
                

                if (randomvector[16] < 0.1)
                    spriteBatch.DrawString(font, currentcarshop.name17, new Vector2(460, 220), Color.BlueViolet);
                
                if (randomvector[17] < 0.1)
                    spriteBatch.DrawString(font, currentcarshop.name18, new Vector2(460, 240), Color.BlueViolet);
                
                if (randomvector[18] < 0.1)
                    spriteBatch.DrawString(font, currentcarshop.name19, new Vector2(460, 260), Color.BlueViolet);
                
                if (randomvector[19] < 0.1)
                    spriteBatch.DrawString(font, currentcarshop.name20, new Vector2(460, 280), Color.BlueViolet);
                
                if (randomvector[20] < 0.05)
                    spriteBatch.DrawString(font, currentcarshop.name21, new Vector2(460, 300), Color.BlueViolet);
                
                if (randomvector[21] < 0.05)
                    spriteBatch.DrawString(font, currentcarshop.name22, new Vector2(460, 320), Color.BlueViolet);

                if (randomvector[22] < 0.05)
                    spriteBatch.DrawString(font, currentcarshop.name23, new Vector2(460, 340), Color.BlueViolet);

                if (randomvector[23] < 0.05)
                    spriteBatch.DrawString(font, currentcarshop.name24, new Vector2(460, 360), Color.BlueViolet);

                if (randomvector[24] < 0.05)
                    spriteBatch.DrawString(font, currentcarshop.name25, new Vector2(460, 380), Color.BlueViolet);
                
                if (randomvector[25] < 0.03)
                    spriteBatch.DrawString(font, currentcarshop.name26, new Vector2(460, 400), Color.BlueViolet);

                if (randomvector[26] < 0.03)
                    spriteBatch.DrawString(font, currentcarshop.name27, new Vector2(460, 420), Color.BlueViolet);

                if (randomvector[27] < 0.03)
                    spriteBatch.DrawString(font, currentcarshop.name28, new Vector2(460, 440), Color.BlueViolet);

                if (randomvector[28] < 0.03)
                    spriteBatch.DrawString(font, currentcarshop.name29, new Vector2(460, 460), Color.BlueViolet);

                if (randomvector[29] < 0.03)
                    spriteBatch.DrawString(font, currentcarshop.name30, new Vector2(460, 480), Color.BlueViolet);

                if (randomvector[30] < 0.01)
                    spriteBatch.DrawString(font, currentcarshop.name31, new Vector2(460, 500), Color.BlueViolet);

                if (randomvector[31] < 0.01)
                    spriteBatch.DrawString(font, currentcarshop.name32, new Vector2(460, 520), Color.BlueViolet);
                
            }
            if (menu == 4)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, "Dyno", new Vector2(260, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "Customize ECU", new Vector2(260, 260), Color.BlueViolet);
            }
            if (menu == 4.1)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, "250  +   " + rpm250.Y, new Vector2(260, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "500  +   " + rpm500.Y, new Vector2(260, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "750  +   " + rpm750.Y, new Vector2(260, 260), Color.BlueViolet);
                spriteBatch.DrawString(font, "1000  +  " + rpm1000.Y, new Vector2(260, 280), Color.BlueViolet);
                spriteBatch.DrawString(font, "1250  +  " + rpm1250.Y, new Vector2(260, 300), Color.BlueViolet);
                spriteBatch.DrawString(font, "1500  +  " + rpm1500.Y, new Vector2(260, 320), Color.BlueViolet);
                spriteBatch.DrawString(font, "1750  +  " + rpm1750.Y, new Vector2(260, 340), Color.BlueViolet);
                spriteBatch.DrawString(font, "2000  +  " + rpm2000.Y, new Vector2(260, 360), Color.BlueViolet);
                spriteBatch.DrawString(font, "2250  +  " + rpm2250.Y, new Vector2(260, 380), Color.BlueViolet);
                spriteBatch.DrawString(font, "2500  +  " + rpm2500.Y, new Vector2(260, 400), Color.BlueViolet);
                spriteBatch.DrawString(font, "2750  +  " + rpm2750.Y, new Vector2(260, 420), Color.BlueViolet);
                spriteBatch.DrawString(font, "3000  +  " + rpm3000.Y, new Vector2(260, 440), Color.BlueViolet);
                spriteBatch.DrawString(font, "3250  +  " + rpm3250.Y, new Vector2(260, 460), Color.BlueViolet);
                spriteBatch.DrawString(font, "3500  +  " + rpm3500.Y, new Vector2(260, 480), Color.BlueViolet);
                spriteBatch.DrawString(font, "3750  +  " + rpm3750.Y, new Vector2(260, 500), Color.BlueViolet);
                spriteBatch.DrawString(font, "4000  +  " + rpm4000.Y, new Vector2(260, 520), Color.BlueViolet);
                spriteBatch.DrawString(font, "4250  +  " + rpm4250.Y, new Vector2(260, 540), Color.BlueViolet);
                spriteBatch.DrawString(font, "4500  +  " + rpm4500.Y, new Vector2(260, 560), Color.BlueViolet);
                spriteBatch.DrawString(font, "4750  +  " + rpm4750.Y, new Vector2(260, 580), Color.BlueViolet);
                spriteBatch.DrawString(font, "5000  +  " + rpm5000.Y, new Vector2(260, 600), Color.BlueViolet);
                spriteBatch.DrawString(font, "5250  +  " + rpm5250.Y, new Vector2(260, 620), Color.BlueViolet);
                spriteBatch.DrawString(font, "5500  +  " + rpm5500.Y, new Vector2(260, 640), Color.BlueViolet);
                spriteBatch.DrawString(font, "5750  +  " + rpm5750.Y, new Vector2(260, 660), Color.BlueViolet);
                spriteBatch.DrawString(font, "6000  +  " + rpm6000.Y, new Vector2(260, 680), Color.BlueViolet);
                spriteBatch.DrawString(font, "6250  +  " + rpm6250.Y, new Vector2(260, 700), Color.BlueViolet);
                spriteBatch.DrawString(font, "6500  +  " + rpm6500.Y, new Vector2(260, 720), Color.BlueViolet);
                spriteBatch.DrawString(font, "6750  +  " + rpm6750.Y, new Vector2(260, 740), Color.BlueViolet);
                spriteBatch.DrawString(font, "7000  +  " + rpm7000.Y, new Vector2(260, 760), Color.BlueViolet);
                spriteBatch.DrawString(font, "7250  +  " + rpm7250.Y, new Vector2(260, 780), Color.BlueViolet);
                spriteBatch.DrawString(font, "7500  +  " + rpm7500.Y, new Vector2(260, 800), Color.BlueViolet);
                spriteBatch.DrawString(font, "7750  +  " + rpm7750.Y, new Vector2(260, 820), Color.BlueViolet);
                spriteBatch.DrawString(font, "8000  +  " + rpm8000.Y, new Vector2(260, 840), Color.BlueViolet);
                spriteBatch.DrawString(font, "8250  +  " + rpm8250.Y, new Vector2(260, 860), Color.BlueViolet);
                spriteBatch.DrawString(font, "8500  +  " + rpm8500.Y, new Vector2(260, 880), Color.BlueViolet);
                spriteBatch.DrawString(font, "8750  +  " + rpm8750.Y, new Vector2(260, 900), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 260), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 280), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 300), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 320), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 340), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 360), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 380), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 400), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 420), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 440), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 460), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 480), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 500), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 520), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 540), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 560), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 580), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 600), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 620), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 640), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 660), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 680), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 700), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 720), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 740), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 760), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 780), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 800), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 820), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 840), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 860), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 880), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(360, 900), Color.BlueViolet);
                spriteBatch.DrawString(font, "+", new Vector2(460, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(460, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "     maxrpm  +  " + maxrpm, new Vector2(460, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "+", new Vector2(460, 280), Color.BlueViolet);
                spriteBatch.DrawString(font, "-", new Vector2(460, 300), Color.BlueViolet);
                spriteBatch.DrawString(font, "     launchrpm  +  " + launchrpm, new Vector2(460, 300), Color.BlueViolet);
            }
            if (menu == 5)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee1, new Vector2(260, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee2, new Vector2(260, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee3, new Vector2(260, 260), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee4, new Vector2(260, 280), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee5, new Vector2(260, 300), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee6, new Vector2(260, 320), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee7, new Vector2(260, 340), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee8, new Vector2(260, 360), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee9, new Vector2(260, 380), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee10, new Vector2(260, 400), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee11, new Vector2(260, 420), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee12, new Vector2(260, 440), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee13, new Vector2(260, 460), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee14, new Vector2(260, 480), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee15, new Vector2(260, 500), Color.BlueViolet);
                spriteBatch.DrawString(font, currentpartshop.namee16, new Vector2(260, 520), Color.BlueViolet);
            }

            if (menu == 6)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Exit", new Vector2(260, 200), Color.BlueViolet);
                spriteBatch.DrawString(font, "", new Vector2(260, 220), Color.BlueViolet);
                spriteBatch.DrawString(font, "keyboard", new Vector2(260, 240), Color.BlueViolet);
                spriteBatch.DrawString(font, "mouse", new Vector2(260, 260), Color.BlueViolet);
            }

            if (menu == 10)
            {
                spriteBatch.Draw(mainmenu, new Vector2(190, 190), Color.White);
                spriteBatch.Draw(arrow, new Vector2(arrowx, arrowy), Color.White);
                spriteBatch.DrawString(font, "Back", new Vector2(260, 200), Color.BlueViolet);
                for (int i = 0; i < maxrpm / 10; i++)
                {
                    spriteBatch.Draw(bluepixel, new Vector2(i * 1680 / (float)(maxrpm / 10), 1050 - (float)(torquevector[i]) * 720 / (float)(torquevector.Max() / 1.2)), Color.White);
                    spriteBatch.Draw(redpixel, new Vector2(i * 1680 / (float)(maxrpm / 10), 1050 - (float)(hpvector[i]) * 720 / (float)(hpvector.Max() / 1.2)), Color.White);
                    spriteBatch.Draw(yellowpixel, new Vector2(i * 1680 / (float)(maxrpm / 10), 1050 - (float)(boostvector[i]) * 720 / (float)(boostvector.Max())), Color.White);
                }
                spriteBatch.DrawString(font, (int)hpvector.Max() + "HP", new Vector2(900, 140), Color.Red);
                spriteBatch.DrawString(font, (int)torquevector.Max() + "NM", new Vector2(900, 160), Color.Blue);
                spriteBatch.DrawString(font, ((float)((int)(boostvector.Max() * 100))) / 100 + "Bar", new Vector2(900, 180), Color.Yellow);
            }

            //spriteBatch.DrawString(font, "loadtransfer: " + (double)(loadtransfer), new Vector2(20, 100), Color.Black);
            //spriteBatch.DrawString(font, "HOLD SHIFT TO LAUNCH", new Vector2(400, 100), Color.Black);
            spriteBatch.DrawString(font, "x: " + (double)(positionx), new Vector2(20, 120), Color.Black);
            spriteBatch.DrawString(font, "y: " + (double)(positiony), new Vector2(220, 120), Color.Black);
            spriteBatch.DrawString(font, "z: " + (double)(positionz), new Vector2(420, 120), Color.Black);
            //spriteBatch.DrawString(font, "vx: " + (double)(speedx), new Vector2(20, 140), Color.Black);
            //spriteBatch.DrawString(font, "vy: " + (double)(speedy), new Vector2(220, 140), Color.Black);
            //spriteBatch.DrawString(font, "vz: " + (double)(speedz), new Vector2(420, 140), Color.Black);
            //spriteBatch.DrawString(font, "dx: " + (double)(dx), new Vector2(20, 600), Color.Black);
            //spriteBatch.DrawString(font, "dy: " + (double)(dy), new Vector2(220, 600), Color.Black);
            //spriteBatch.DrawString(font, "dz: " + (double)(dz), new Vector2(420, 600), Color.Black);
            //spriteBatch.DrawString(font, "speed: " + (double)(speed), new Vector2(20, 160), Color.Black);
            //spriteBatch.DrawString(font, "rpm: " + (int)(rpm), new Vector2(20, 180), Color.Black);
            //spriteBatch.DrawString(font, "springposlf: " + (double)(springrfpos2), new Vector2(20, 220), Color.Black);
            //spriteBatch.DrawString(font, "springspeedlf: " + (double)(springrfspeed2), new Vector2(20, 240), Color.Black);
            //spriteBatch.DrawString(font, "springposlb: " + (double)(springrbpos2), new Vector2(20, 260), Color.Black);
            //spriteBatch.DrawString(font, "springspeedlb: " + (double)(springrbspeed2), new Vector2(20, 280), Color.Black);
            //spriteBatch.DrawString(font, "xangle: " + (double)(xangle2), new Vector2(20, 300), Color.Black);
            //spriteBatch.DrawString(font, "springposrf: " + (double)(springlfpos2), new Vector2(320, 220), Color.Black);
            //spriteBatch.DrawString(font, "springspeedrf: " + (double)(springlfspeed2), new Vector2(320, 240), Color.Black);
            //spriteBatch.DrawString(font, "springposrb: " + (double)(springlbpos2), new Vector2(320, 260), Color.Black);
            //spriteBatch.DrawString(font, "springspeedrb: " + (double)(springlbspeed2), new Vector2(320, 280), Color.Black);
            //spriteBatch.DrawString(font, "y2angle: " + (double)(y2angle), new Vector2(320, 300), Color.Black);

            //spriteBatch.DrawString(font, "wheelposlfx: " + (double)(wheelposlfx), new Vector2(320, 340), Color.Black);
            //spriteBatch.DrawString(font, "wheelposlfy: " + (double)(wheelposlfy), new Vector2(320, 360), Color.Black);
            //spriteBatch.DrawString(font, "wheelposlbx: " + (double)(wheelposlbx), new Vector2(320, 400), Color.Black);
            //spriteBatch.DrawString(font, "wheelposlby: " + (double)(wheelposlby), new Vector2(320, 420), Color.Black);

            //spriteBatch.DrawString(font, "wheelposrfz: " + (double)(wheelposrfz), new Vector2(20, 340), Color.Black);
            //spriteBatch.DrawString(font, "wheelposlfz: " + (double)(wheelposlfz), new Vector2(20, 360), Color.Black);
            //spriteBatch.DrawString(font, "wheelposrbz: " + (double)(wheelposrbz), new Vector2(20, 400), Color.Black);
            //spriteBatch.DrawString(font, "wheelposlbz: " + (double)(wheelposlbz), new Vector2(20, 420), Color.Black);

            //spriteBatch.DrawString(font, "floorrf: " + (double)(floorrf), new Vector2(20, 480), Color.Black);
            //spriteBatch.DrawString(font, "floorlf: " + (double)(floorlf), new Vector2(20, 500), Color.Black);
            //spriteBatch.DrawString(font, "floorrb: " + (double)(floorrb), new Vector2(20, 520), Color.Black);
            //spriteBatch.DrawString(font, "floorlb: " + (double)(floorlb), new Vector2(20, 540), Color.Black);

            spriteBatch.DrawString(font, "griprf2: " + (double)(griprf2), new Vector2(220, 480), Color.Black);
            spriteBatch.DrawString(font, "griplf2: " + (double)(griplf2), new Vector2(220, 500), Color.Black);
            spriteBatch.DrawString(font, "griprb2: " + (double)(griprb2), new Vector2(220, 520), Color.Black);
            spriteBatch.DrawString(font, "griplb2: " + (double)(griplb2), new Vector2(220, 540), Color.Black);

            spriteBatch.DrawString(font, "griprf: " + (double)(griprf), new Vector2(420, 480), Color.Black);
            spriteBatch.DrawString(font, "griplf: " + (double)(griplf), new Vector2(420, 500), Color.Black);
            spriteBatch.DrawString(font, "griprb: " + (double)(griprb), new Vector2(420, 520), Color.Black);
            spriteBatch.DrawString(font, "griplb: " + (double)(griplb), new Vector2(420, 540), Color.Black);

            //spriteBatch.DrawString(font, "xangle: " + (double)(xangle), new Vector2(520, 480), Color.Black);
            //spriteBatch.DrawString(font, "yangle: " + (double)(yangle), new Vector2(520, 500), Color.Black);
            //spriteBatch.DrawString(font, "x2angle: " + (double)(x2angle), new Vector2(520, 520), Color.Black);
            //spriteBatch.DrawString(font, "y2angle: " + (double)(y2angle), new Vector2(520, 540), Color.Black);

            //spriteBatch.DrawString(font, "control: arrows", new Vector2(20, 460), Color.Black);
            //spriteBatch.DrawString(font, "shift up/down: a/z", new Vector2(20, 480), Color.Black);
            //spriteBatch.DrawString(font, "clutch: space", new Vector2(20, 500), Color.Black);
            //spriteBatch.DrawString(font, "launch: shift", new Vector2(20, 520), Color.Black);
            //spriteBatch.DrawString(font, "camera: 1,2,3,4,5,6", new Vector2(20, 540), Color.Black);
            //spriteBatch.DrawString(font, "menu control: arrows,enter", new Vector2(20, 560), Color.Black);


            //spriteBatch.DrawString(font, "horizontalangle: " + (int)(MathHelper.ToDegrees((float)horizontalangle)), new Vector2(220, 720), Color.Black);
            //spriteBatch.DrawString(font, "gravitysteer: " + (double)(gravitysteer), new Vector2(220, 740), Color.Black);

            //spriteBatch.DrawString(font, "loadtransferside: " + (double)(loadtransferside), new Vector2(600, 40), Color.Black);
            spriteBatch.DrawString(font, "stationary: " + (bool)(stationary), new Vector2(600, 60), Color.Black);
            //spriteBatch.DrawString(font, "slope: " + (int)(MathHelper.ToDegrees((float)slopeangle)), new Vector2(600, 80), Color.Black);
            //spriteBatch.DrawString(font, "gravityacc: " + (double)(gravityacceleration), new Vector2(600, 100), Color.Black);
            //spriteBatch.DrawString(font, "rollover: " + (bool)(rollover), new Vector2(600, 120), Color.Black);

            //spriteBatch.DrawString(font, "checklength " + (double)(checkpointx.Length), new Vector2(520, 600), Color.Black);
            spriteBatch.DrawString(font, "steerforce " + (double)(steerforce), new Vector2(520, 580), Color.Black);
            spriteBatch.DrawString(font, "angularacc " + (double)(angularacceleration), new Vector2(520, 620), Color.Black);
            spriteBatch.DrawString(font, "steer " + (double)(steer), new Vector2(520, 660), Color.Black);
            spriteBatch.DrawString(font, "acceleration" + (double)(acceleration), new Vector2(520, 680), Color.Black);
            spriteBatch.DrawString(font, "acceleration2 " + (double)(acceleration2), new Vector2(520, 700), Color.Black);
            spriteBatch.DrawString(font, "torque " + (int)(maxtorque), new Vector2(1320, 700), Color.Black);
            spriteBatch.DrawString(font, "horsepower " + (int)(maxtorque * 2 * Math.PI * rpm * 1.34 / 60000), new Vector2(1320, 720), Color.Black);
            spriteBatch.DrawString(font, "0-80 " + (double)(trap1), new Vector2(1320, 740), Color.Black);
            spriteBatch.DrawString(font, "0-100 " + (double)(trap2), new Vector2(1320, 757), Color.Black);
            spriteBatch.DrawString(font, "0-160 " + (double)(trap3), new Vector2(1320, 774), Color.Black);
            spriteBatch.DrawString(font, "402m " + (double)(trap4), new Vector2(1320, 791), Color.Black);
            spriteBatch.DrawString(font, "finish time " + (double)(trap5), new Vector2(1320, 808), Color.Black);
            spriteBatch.DrawString(font, "wheelmoi " + (int)(wheelmoif + wheelmoir), new Vector2(1320, 823), Color.Black);
            //spriteBatch.DrawString(font, "drag " + (double)(drag), new Vector2(1320, 840), Color.Black);
            //spriteBatch.DrawString(font, "rollingress " + (double)(rollingres), new Vector2(1320, 860), Color.Black);

            spriteBatch.DrawString(font, "turbosize " + (double)(turbosize), new Vector2(20, 800), Color.Black);
            spriteBatch.DrawString(font, "exhaust " + (double)(ve * (1 + currentboost) * rpm / 60 * displacement / 1000 / stroketype * 1.45), new Vector2(20, 820), Color.Black);
            spriteBatch.DrawString(font, "exhaustmax " + (double)(exhaustmax), new Vector2(20, 840), Color.Black);
            spriteBatch.DrawString(font, "random " + (double)(randomvector[1]), new Vector2(20, 860), Color.Black);
            spriteBatch.DrawString(font, "gear2 " + (int)(gear2), new Vector2(20, 880), Color.Black);
            spriteBatch.DrawString(font, "ratio2 " + (double)(ratio2), new Vector2(20, 900), Color.Black);
            spriteBatch.DrawString(font, "speed2 " + (double)(speed2), new Vector2(20, 920), Color.Black);
            spriteBatch.DrawString(font, "torque2 " + (double)(maxtorque2), new Vector2(20, 940), Color.Black);
            spriteBatch.DrawString(font, "positiony2 " + (double)(positiony2), new Vector2(20, 960), Color.Black);
            
            //spriteBatch.DrawString(font, "direction " + (int)(direction), new Vector2(20, 700), Color.Black);
            //spriteBatch.DrawString(font, "worlddistance " + (int)(worlddistance), new Vector2(700, 400), Color.Black);

            spriteBatch.DrawString(font, "finish " + (bool)finish, new Vector2(900, 420), Color.Black);
            //spriteBatch.DrawString(font, "checkpoint " + (int)(checkpoint), new Vector2(900, 440), Color.Black);
            //spriteBatch.DrawString(font, "max.x " + (float)(boundingbox1.Max.X), new Vector2(900, 460), Color.Black);
            //spriteBatch.DrawString(font, "max.y " + (float)(boundingbox1.Max.Y), new Vector2(900, 480), Color.Black);
            //spriteBatch.DrawString(font, "max.z " + (float)(boundingbox1.Max.Z), new Vector2(900, 500), Color.Black);
            //spriteBatch.DrawString(font, "min.x " + (float)(boundingbox1.Min.X), new Vector2(900, 520), Color.Black);
            //spriteBatch.DrawString(font, "min.y " + (float)(boundingbox1.Min.Y), new Vector2(900, 540), Color.Black);
            //spriteBatch.DrawString(font, "min.z " + (float)(boundingbox1.Min.Z), new Vector2(900, 560), Color.Black);
            //spriteBatch.DrawString(font, "max.x " + (float)(cubebox.Max.X), new Vector2(900, 580), Color.Black);
            //spriteBatch.DrawString(font, "max.y " + (float)(cubebox.Max.Y), new Vector2(900, 600), Color.Black);
            //spriteBatch.DrawString(font, "max.z " + (float)(cubebox.Max.Z), new Vector2(900, 620), Color.Black);
            //spriteBatch.DrawString(font, "min.x " + (float)(cubebox.Min.X), new Vector2(900, 640), Color.Black);
            //spriteBatch.DrawString(font, "min.y " + (float)(cubebox.Min.Y), new Vector2(900, 660), Color.Black);
            //spriteBatch.DrawString(font, "collision " + (bool)(collision), new Vector2(900, 680), Color.Black);
            spriteBatch.End();
            base.Draw(gameTime);

        }

        /// <summary>
        /// Does the work of drawing a model, given specific world, view, and projection
        /// matrices.
        /// </summary>
        /// <param name="model">The model to draw</param>
        /// <param name="world">The transformation matrix to get the model in the right place in the world.</param>
        /// <param name="view">The transformation matrix to get the model in the right place, relative to the camera.</param>
        /// <param name="projection">The transformation matrix to project the model's points onto the screen correctly.</param>
        private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;
                }

                mesh.Draw();
            }
        }


        public void DrawBillboard()
        {
            GraphicsDevice.SetVertexBuffer(billboard.vertexBuffer);
            GraphicsDevice.Indices = billboard.indexBuffer;

            RasterizerState prevRasterizerState = GraphicsDevice.RasterizerState;
            BlendState prevBlendState = GraphicsDevice.BlendState;

            GraphicsDevice.BlendState = BlendState.NonPremultiplied;
            GraphicsDevice.RasterizerState = RasterizerState.CullNone;

            // Create a matrix that will rotate the billboard so that it will
            // always face the camera.
            billboard.texture = Content.Load<Texture2D>("grass");
            for (int i = 0; i < 50; i++)
            {
                Matrix billboardMatrix = Matrix.CreateConstrainedBillboard(new Vector3((float)(-41 + randomvector2[99 - i] * 8), i * 10, 0),
    cameraposition, Vector3.UnitZ, cameradirection, Vector3.UnitY);


                billboardeffect.Parameters["world"].SetValue(billboardMatrix);
                billboardeffect.Parameters["view"].SetValue(view);
                billboardeffect.Parameters["projection"].SetValue(projection);
                billboardeffect.Parameters["colorMap"].SetValue(billboard.texture);

                foreach (EffectPass pass in billboardeffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                        0, 0, billboard.vertexBuffer.VertexCount, 0, 2);
                }
            }
            billboard.texture = Content.Load<Texture2D>("tree");
            for (int i = 0; i < 50; i++)
            {
                Matrix billboardMatrix = Matrix.CreateScale(2, 2, 2) * Matrix.CreateConstrainedBillboard(new Vector3((float)(-43 + randomvector2[i] * 10), i * 15 + 2, -1),
    cameraposition, Vector3.UnitZ, cameradirection, Vector3.UnitY);


                billboardeffect.Parameters["world"].SetValue(billboardMatrix);
                billboardeffect.Parameters["view"].SetValue(view);
                billboardeffect.Parameters["projection"].SetValue(projection);
                billboardeffect.Parameters["colorMap"].SetValue(billboard.texture);

                foreach (EffectPass pass in billboardeffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                        0, 0, billboard.vertexBuffer.VertexCount, 0, 2);
                }
            }


            GraphicsDevice.SetVertexBuffer(null);
            GraphicsDevice.Indices = null;

            GraphicsDevice.BlendState = prevBlendState;
            GraphicsDevice.RasterizerState = prevRasterizerState;
        }


        private void DrawTerrain(Matrix currentViewMatrix)
        {
            effect.CurrentTechnique = effect.Techniques["MultiTextured"];
            effect.Parameters["xTexture0"].SetValue(currenttexture1);
            effect.Parameters["xTexture1"].SetValue(currenttexture2);
            effect.Parameters["xTexture2"].SetValue(currenttexture3);
            effect.Parameters["xTexture3"].SetValue(currenttexture4);


            effect.Parameters["xWorld"].SetValue(worldt1);
            effect.Parameters["xView"].SetValue(view);
            effect.Parameters["xProjection"].SetValue(projection);

            effect.Parameters["xEnableLighting"].SetValue(true);
            effect.Parameters["xAmbient"].SetValue(0.4f);
            effect.Parameters["xLightDirection"].SetValue(new Vector3(-0.5f, -1, -0.5f));



            if (Distance(worldt1.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer;
                    device.SetVertexBuffer(terrainVertexBuffer);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);          
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt2);
            if (Distance(worldt2.Translation, positionvector) < 200)
            {       
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer2;
                    device.SetVertexBuffer(terrainVertexBuffer2);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt3);
            if (Distance(worldt3.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer3;
                    device.SetVertexBuffer(terrainVertexBuffer3);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt4);
            if (Distance(worldt4.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer4;
                    device.SetVertexBuffer(terrainVertexBuffer4);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt5);
            if (Distance(worldt5.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer5;
                    device.SetVertexBuffer(terrainVertexBuffer5);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt6);
            if (Distance(worldt6.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer6;
                    device.SetVertexBuffer(terrainVertexBuffer6);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt7);
            if (Distance(worldt7.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer7;
                    device.SetVertexBuffer(terrainVertexBuffer7);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt8);
            if (Distance(worldt8.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer8;
                    device.SetVertexBuffer(terrainVertexBuffer8);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt9);
            if (Distance(worldt9.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer9;
                    device.SetVertexBuffer(terrainVertexBuffer9);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt10);
            if (Distance(worldt10.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer10;
                    device.SetVertexBuffer(terrainVertexBuffer10);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt11);
            if (Distance(worldt11.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer11;
                    device.SetVertexBuffer(terrainVertexBuffer11);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt12);
            if (Distance(worldt12.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer12;
                    device.SetVertexBuffer(terrainVertexBuffer12);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt13);
            if (Distance(worldt13.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer13;
                    device.SetVertexBuffer(terrainVertexBuffer13);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt14);
            if (Distance(worldt14.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer14;
                    device.SetVertexBuffer(terrainVertexBuffer14);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt15);
            if (Distance(worldt15.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer15;
                    device.SetVertexBuffer(terrainVertexBuffer15);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }

            effect.Parameters["xWorld"].SetValue(worldt16);
            if (Distance(worldt16.Translation, positionvector) < 200)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    device.Indices = terrainIndexBuffer16;
                    device.SetVertexBuffer(terrainVertexBuffer16);
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 1, 0, f / 3);
                }
            }




        }

    }
}
